【问题标题】:Requests using Beautiful Soup gets blocked使用 Beautiful Soup 的请求被阻止
【发布时间】:2017-04-16 18:07:29
【问题描述】:

当我使用 Beautiful Soup 提出请求时,我作为“机器人”被阻止。

import requests
from bs4 import BeautifulSoup

reddit1Link = requests.get("https://www.reddit.com/r/tensorflow/comments/650p49/question_im_a_techy_35_year_old_and_i_think_ai_is/")
reddit1Content =BeautifulSoup(reddit1Link.content,"lxml")
print(reddit1Content)

然后我从 Reddit 收到消息说他们怀疑我是机器人。

Beautiful Soup 有哪些可能的解决方案? (我曾尝试使用 Scrapy 使用它的 Crawlera,但由于我缺乏 python 知识,我无法使用它。)我不介意它是否是付费服务,只要它对初学者来说足够“直观”即可使用。

【问题讨论】:

    标签: web-scraping beautifulsoup


    【解决方案1】:

    作为机器人被阻止的原因可能有多种。

    当您“按原样”使用请求库时,阻止的最可能原因是缺少用户代理标头。

    针对机器人和抓取的第一道防线是检查用户代理标头是否来自主要浏览器之一,并阻止所有非浏览器用户代理。

    短版:试试这个:

    import requests
    from bs4 import BeautifulSoup
    
    headers = requests.utils.default_headers()
    headers.update({
        'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0',
    })
    
    reddit1Link = requests.get("https://www.reddit.com/r/tensorflow/comments/650p49/question_im_a_techy_35_year_old_and_i_think_ai_is/", headers=headers)
    reddit1Content =BeautifulSoup(reddit1Link.content,"lxml")
    print(reddit1Content)
    

    详细说明: Sending "User-agent" using Requests library in Python

    【讨论】:

      【解决方案2】:

      我曾经用 Mechanize 来做这样的事情,已经有几年了,但它应该仍然可以工作。

      试试这样的:

      from mechanize import Browser
      from bs4 import BeautifulSoup
      
      b = Browser()
      b.set_handle_robots(False)
      b.addheaders = [('Referer', 'https://www.reddit.com'), ('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1')]
      
      b.open('https://www.reddit.com/r/tensorflow/comments/650p49/question_im_a_techy_35_year_old_and_i_think_ai_is/')
      soup = BeautifulSoup(b.response().read(), "html.parser")
      

      编辑:

      我刚刚意识到,遗憾的是,mechanize 仅适用于 python 2.5-2.7,但是,还有其他可用选项。见Installing mechanize for python 3.4

      【讨论】:

      • 感谢 Raudbjorn!这不适用于 python 3,是吗?
      • 不,抱歉,请参阅我编辑的答案。但是其他库确实允许您添加标题并关闭机器人处理;请记住,稍微限制一下可能是个好主意,否则您可能会“被抓住”,在每个请求之后使用 time.sleep(1) 以避免被识别为机器人。
      • 从0.4.0版本开始就已经支持python3,所以我从答案中删除了参考。
      猜你喜欢
      • 2015-07-04
      • 1970-01-01
      • 2018-09-09
      • 1970-01-01
      • 2015-06-22
      • 2019-11-04
      • 2017-02-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多