我有以下脚本,我想从文本文件而不是数组检索URL的。 我是Python的新手,而且一直被困住!
from bs4 import BeautifulSoup
import requests
urls = ['URL1',
'URL2',
'URL3']
for u in urls:
response = requests.get(u)
data = response.text
soup = BeautifulSoup(data,'lxml')
请你说清楚一点你想要什么好吗?
下面是一个可能的答案,它可能是你想要的,也可能不是你想要的:
from bs4 import BeautifulSoup
import requests
with open('yourfilename.txt', 'r') as url_file:
for line in url_file:
u = line.strip()
response = requests.get(u)
data = response.text
soup = BeautifulSoup(data,'lxml')
文件是用open()
函数打开的; 第二个参数是'r'
,用于指定以只读模式打开它。 对open()
的调用封装在with
块中,因此一旦您不再需要打开文件,该文件就会自动关闭。 stripe()
函数删除每行开头和结尾的尾随空格(空格,制表符,换行符),使'https://stackoverflow.com'.stripe()
立即变为'https://stackoverflow.com'
。