【问题标题】:Why does requests module load different content than my browser?为什么请求模块加载的内容与我的浏览器不同?
【发布时间】:2020-05-24 09:08:52
【问题描述】:

我有以下 Python 代码:

req=requests.get("https://pythonhow.com/example.html")
content=req.content
soup=BeautifulSoup(content, "html.parser")
all=soup.find_all(attrs={"class": "cities"})

当我将此 URL 粘贴到浏览器中时,我得到了预期的标记结构:

<body data-gr-c-s-loaded="true" cz-shortcut-listen="true">
    <h1 align="center"> Here are three big cities </h1>
    <div class="cities">
        <h2>London</h2>
        <p>London is the capital of England and it's been a British settlement since 2000 years ago. </p>
    </div>
    <div class="cities">
        <h2>Paris</h2>
        <p>Paris is the capital city of France. It was declared capital since 508.</p>
    </div>
    <div class="cities">
        <h2>Tokyo</h2>
        <p>Tokyo is the capital of Japan and one of the most populated cities in the world.</p>
    </div>
</body>

然而,当我检查 requests.get 内容时,我有以下 HTML:

<head>
    <title>Not Acceptable!</title>
</head>
<body>
    <h1>Not Acceptable!</h1>
    <p>An appropriate representation of the requested resource could not be found on this server. This error was generated by Mod_Security.</p>
</body>

为什么requests 获取的内容与我的浏览器不同?我怀疑它与某些请求标头有关,但我不知道从哪里开始。

【问题讨论】:

    标签: python python-3.x http beautifulsoup python-requests


    【解决方案1】:

    这都是关于 headers 网站验证您针对机器人的请求的地方。

    如您所见,在您的请求中,Mod_Security Web 应用程序防火墙 (WAF) 阻止了它。因此,您只需添加标头并发送GET 请求。此外,您应该始终检查第一个请求,通过打印r 来检查响应,这是请求的一个变量。

    import requests
    from bs4 import BeautifulSoup
    
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:76.0) Gecko/20100101 Firefox/76.0'
    }
    
    
    def main(url):
        r = requests.get(url, headers=headers)
        print(r)
        soup = BeautifulSoup(r.content, 'html.parser')
        print(soup.prettify())
    
    
    main("https://pythonhow.com/example.html")
    

    【讨论】:

      【解决方案2】:

      您收到的错误是“请原谅我们的打扰。您的浏览器的某些问题让我们认为您是机器人”。表示不允许抓取,并且他们的网页上有反抓取机器人。您需要添加headers。你可以试试:

      headers = {'User-Agent': 'Mozilla/5.0 (Windows NT x.y; Win64; x64; rv:10.0) Gecko/20100101 Firefox/10.0 '}
      req=requests.get("https://pythonhow.com/example.html", headers=headers)
      content=req.content
      soup=BeautifulSoup(content, "html.parser")
      all=soup.find_all(attrs={"class": "cities"})
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-04-25
        • 2016-01-11
        • 2011-09-06
        • 1970-01-01
        • 2014-03-30
        • 1970-01-01
        • 2021-11-06
        相关资源
        最近更新 更多