繁体   English   中英

当给定包含URL的变量时,requests.get返回400个错误的URL,但是当给定具有相同URL的字符串时,则不会返回400个错误的URL。

[英]requests.get returns 400 bad url when given a variable containing a url, but not when given a string with the same url

我有一个程序,该程序从文本文件中读取一些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

等等

提前致谢。

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

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

还有其他从行中删除空格的方法,请看这篇文章: 使用.readlines()时摆脱\\ n

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM