提问者:小点点

基于列表的Python请求


我有一个包含如下条目的文本文件(url.py):

import requests

headers = {
'authority': 'www.spain.com',
'pragma': 'no-cache',
'cache-control': 'no-cache',
'upgrade-insecure-requests': '1',
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.106 Safari/537.36',
'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
'sec-fetch-site': 'none',
'sec-fetch-mode': 'navigate',
'sec-fetch-user': '?1',
'sec-fetch-dest': 'document',
'accept-language': 'en-US,en;q=0.9,pt;q=0.8',
}

links=['https://www.spain.com']
for url in links:
    page = requests.get(url, headers=headers)
    print(page)

返回

ubuntu@OS-Ubuntu:/mnt/$ python3 url.py
<Response [200]>

我需要自动填写,因为我将收到一个txt文件(domain.txt),其中包含如下所示的域:

www.spain.com
www.uk.com
www.italy.com

我希望python脚本是唯一的和横向的。。。我只需要向我的domain.txt添加更多的域,然后运行我的url.py,它会自动对domain.txt的所有域发出请求

你可以帮我。


共1个答案

匿名用户

假设url.py与domains.txt位于同一个目录中,您可以打开该文件,并使用以下方法将每个链接读入一个列表:

with open('domains.txt', 'r') as f:
    links = f.read().splitlines()