[英]requests.get returns 403 while the same url works in browser
[英]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.