在给定包含url的变量时,requests.get返回400个坏URL,但在给定具有相同url的字符串时则不返回

时间:2017-10-15 03:46:56

标签: python-3.x file url python-requests

我有一个程序从文本文件中读取一些URL,使用requests.get获取页面源,然后使用beautifulsoup4查找一些信息。

f = open('inputfile.txt')
session = requests.Session()
session.headers.update({'User-Agent': 'Mozilla/5.0'})
for line in f:
    x = 0
    z = len(line)
    r = session.get(line[x:z])
    soup = bs4.BeautifulSoup(r.text, "html.parser")

这将返回HTTP 400错误请求 - 无效的URL。但是,当我做同样的事情,除了输入URL作为字符串,一切正常(虽然我只得到一个URL)。

f = open('inputfile.txt')
session = requests.Session()
session.headers.update({'User-Agent': 'Mozilla/5.0'})
for line in f:
    r = session.get('http://www.ExactSameUrlAsEarlier.com')
    soup = bs4.BeautifulSoup(r.text, "html.parser")

如何修复/修改此操作以允许我循环浏览文件中的多个URL?只是为了澄清,这就是inputfile.txt的样子:

http://www.url1.com/something1
http://www.url2.com/something2

等。

提前致谢。

1 个答案:

答案 0 :(得分:0)

您应该遍历文件中的行,而不是文件句柄。你的for循环应该是:

for line in f.readlines():
    url = line.strip()

还有其他方法可以从该行中删除空白,请看一下这篇文章:Getting rid of \n when using .readlines()