【问题标题】:python-requests and urllib not giving the same HTML as seen in browser, target site only contains text (no apparent scripts)python-requests 和 urllib 没有提供与浏览器中相同的 HTML,目标站点仅包含文本(没有明显的脚本)
【发布时间】:2019-12-27 03:57:09
【问题描述】:

我有以下网址:https://tenhou.net/3/mjlog2xml.cgi?2009042400gm-00b9-0000-3a2a55dc

它只包含文本,我想下载它并使用 Python 将其作为 xml 文件存储在我的磁盘上。我正在使用请求模块。这是我尝试做的事情:

import requests

url = "https://tenhou.net/3/mjlog2xml.cgi?2009042400gm-00b9-0000-3a2a55dc"

r = requests.get(url, allow_redirects=True)
open('test.xml', 'wb').write(r.content)

当我去检查test.xml 的内容时,它只包含文本“请下载原始文件”。我也尝试过使用urllib.request.urlopen(),但我得到了相同的结果。

但是,当我在浏览器中打开 url 时,我会看到完整的标记文本,我什至可以将页面下载为另存为 xml。

我使用 requests 方法收到的 HTML 是:

<html>
   <body>
      <p>PLEASE DOWNLOAD RAW FILE</p>
   </body>
</html>>

但是网站上的 HTML 是like this

我要下载的文本在左边。 HTML 显示在右侧。如果我能得到右边的 HTML,那么我就知道如何使用 BeautifulSoup 之类的东西来解析它并得到我想要的东西。但我不确定为什么 python-requests 和 urllib 没有给我正确的数据。

【问题讨论】:

    标签: html xml python-requests urllib


    【解决方案1】:

    该站点似乎检查了请求中发送的user-agent

    如果您在请求中明确设置类似浏览器的用户代理,您将获得您想要获得的响应:

    import requests
    
    url = "https://tenhou.net/3/mjlog2xml.cgi?2009042400gm-00b9-0000-3a2a55dc"
    
    # Create a dictionary of the headers including the User-Agent
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36'
    }
    
    
    r = requests.get(url, headers=headers, allow_redirects=True)
    open('test.xml', 'wb').write(r.content)
    

    【讨论】:

    • 谢谢,成功了。您如何知道网站是否需要指定用户代理?
    • @f.zs 这是网站后端逻辑的一部分。除非它被记录在任何地方,否则你无法知道。在这种情况下,唯一要做的就是将有效的请求(来自浏览器)与无效的请求(来自 python)进行比较,并开始分析它们之间的差异。
    猜你喜欢
    • 2020-06-17
    • 1970-01-01
    • 2015-07-22
    • 2015-03-17
    • 2012-04-20
    • 2014-11-17
    • 2012-11-15
    • 2023-01-06
    • 2018-12-23
    相关资源
    最近更新 更多