【问题标题】:Redirection in browser is different from python code浏览器中的重定向与python代码不同
【发布时间】:2019-12-17 01:12:07
【问题描述】:

我想用 Python 打开一个网站的链接,流程如下:

  1. 我打开主 URL(例如 www.url1.com)

  2. 我抓取页面并找到按钮,它有一个重定向链接(www.url2.com)

  3. 当我在浏览器中使用此链接时,它会重定向到 (www.url3.com) 然后立即转到另一个(必填链接)(www.url4.com)

  4. 当我使用 Python 请求尝试相同的流程时,它只会转到 (www.url3.com)

  5. 我尝试使用 allow_redirects 参数没有任何成功

这是我的代码:

import requests

headers = {
    'User-Agent': '',
    'authority': '',
    'scheme': '',
    'accept': '',
    'x-requested-with': '',
    'cookie': '',
    'referer': 
    }


def download(req):      
    resp = requests.get(req, headers=headers, allow_redirects=True)
    print(resp.text)

我还尝试使用此answer 打印历史记录。

但它也一直在重定向我 (url3)

【问题讨论】:

  • 如果 url3 使用 refresh meta tag 重定向浏览器,requests 将不会跟随它,即使启用了 allow_redirects,因为它不解析 html。 How to follow meta refresh in python

标签: python http python-requests


【解决方案1】:

如果没有您使用的实际 URL,很难给出完整的答案。话虽如此,我认为问题在于您没有保存/跟踪 cookie,因此我建议您在发送请求时使用requests.session(),因为它会为您跟踪 cookie。

总而言之,我建议尝试以下代码:

import requests

session = requests.session()

headers = {
    'User-Agent': '',
    'authority': '',
    'scheme': '',
    'accept': '',
    'x-requested-with': '',
    'cookie': '',
    'referer': 
    }


def download(req):
    global session
 
    resp = session.get(req, headers=headers, allow_redirects=True)
    print(resp.text)

(PS:如果您要抓取一个网站,我强烈建议您在标题中使用 User-Agent,而不是将其留空)

希望对你有帮助

【讨论】:

  • 引用者也可能改变 url3 的行为
  • @wuerfelfreak 确实!没有实际的网址/网站很难说。
  • @Fozoro 谢谢我尝试了会话,但还没有运气,这里的所有标题都已填满。如果你想要实际的 url:url3(单击按钮打开):egy.best/… 但在浏览器中它重定向到另一个,而在 python 请求中,url3 的 html 中的响应并且没有进一步的重定向
猜你喜欢
  • 1970-01-01
  • 2013-10-24
  • 2013-09-24
  • 2016-05-01
  • 2018-10-28
  • 1970-01-01
  • 2011-05-26
  • 2013-01-23
  • 1970-01-01
相关资源
最近更新 更多