【问题标题】:python urllib.request not getting same html as my browserpython urllib.request 没有得到与我的浏览器相同的 html
【发布时间】:2012-11-21 18:05:27
【问题描述】:

尝试使用以下python代码获取http://groupon.cl/descuentos/santiago-centro的html代码:

import urllib.request
url="http://groupon.cl/descuentos/santiago-centro"
request = urllib.request.Request(url, headers = {'user-agent' : 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'})
response = urllib.request.urlopen(request)
return response.read().decode('utf-8')

我正在获取询问我位置的页面的 html 代码。如果我用浏览器手动打开相同的链接(不涉及 cookie,即使是最近安装的浏览器),我会直接进入折扣促销页面。似乎是一些 urllib 没有发生的重定向操作。我正在使用用户代理标头来尝试获取典型浏览器的行为,但我没有运气。

如何获得与浏览器相同的 html 代码?

【问题讨论】:

    标签: redirect python-3.x user-agent urllib


    【解决方案1】:

    我认为你可以运行这个命令:

    wget -d http://groupon.cl/descuentos/santiago-centro
    

    你会看到 wget 打印两个 http 请求并将响应页面保存到一个文件中。

     -   HTTP/1.1 302 Moved Temporarily
     -   HTTP/1.1 200 OK
    

    文件的内容是你想要的html代码。

    第一个响应码是 302,所以urllib.requst.urlopen 做第二个请求。但它没有 设置从第一个响应中获取的正确 cookie,服务器无法理解 第二个请求,所以你得到另一个页面。

    http.client 模块不自己处理 301 或 302 http 响应。

    import http
    
    conn = http.client.HTTPConnection("groupon.cl")
    #do first request
    conn.request("GET", "/descuentos/santiago-centro")
    print(conn.status)  # 301 or 302
    print(conn.getheaders()) # set-Cookie
    
    #get the cookie
    headers = ....
    #do second request
    
    conn.requesst("GET", "/", headers)
    ......
    ......
    #Get response page.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-23
      • 1970-01-01
      • 1970-01-01
      • 2022-06-12
      • 2020-11-21
      • 1970-01-01
      相关资源
      最近更新 更多