设置allow_redirects=False仍被重定向,请求无内容问题求助
解决requests设置allow_redirects=False仍无法获取目标Stack Overflow页面的问题
你遇到的问题本质是目标Stack Overflow问题已被官方合并到另一问题,而非requests的重定向设置失效:
- 你请求的原问题链接(73909641)在Stack Overflow端已不存在,官方默认将其重定向到合并后的问题(37015073)。
- 当设置
allow_redirects=False时,requests确实不会自动跳转,但此时服务器返回的是3xx状态码的重定向响应,响应内容是官方的重定向提示页,而非原问题内容。
解决方式
直接请求合并后的目标URL
既然原问题已被合并,直接使用重定向后的链接发起请求即可获取对应内容:import requests from bs4 import BeautifulSoup headers = {'User-Agent': '你的User-Agent内容'} # 使用合并后的问题URL URL = "https://stackoverflow.com/questions/37015073/convert-between-byte-count-and-human-readable-string" html_content = requests.get(URL, headers=headers) soup = BeautifulSoup(html_content.content, "html.parser") # 后续可正常解析页面内容验证服务器重定向响应
若要确认重定向的具体信息,可以打印响应状态码和Location字段:import requests headers = {'User-Agent': '你的User-Agent内容'} URL = "https://stackoverflow.com/questions/73909641/program-is-about-space-utilisation-i-am-getting-error-72g-value-too-great-for" html_content = requests.get(URL, allow_redirects=False, headers=headers) # 打印状态码(应为3xx,比如301永久重定向) print(html_content.status_code) # 打印官方指定的重定向地址 print(html_content.headers.get('Location'))
内容的提问来源于stack exchange,提问作者edyvedy13
相关产品推荐
相关产品推荐

