使用Beautiful Soup的请求被阻止

Isa*_*aac 3 beautifulsoup web-scraping

我是Carnegie Mellon的新生,他在第一个任期内完全迷失了方向.

当我使用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)
Run Code Online (Sandbox Code Playgroud)

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

  1. 通过美丽的汤有什么可能的解决方案?(我已经尝试使用Scrapy来使用它的Crawlera,但是由于我缺乏python知识,我无法使用它.)我不介意它是否是付费服务,只要它对于初学者来说足够"直观"使用.

我将衷心感谢您的帮助.

此致

艾萨克李

Don*_*ons 8

被阻止作为机器人可能有各种原因.

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

防止机器人和抓取的第一道防线是检查用户代理标头是否来自其中一个主要浏览器并阻止所有非浏览器用户代理.

短版:试试这个:

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)
Run Code Online (Sandbox Code Playgroud)

详细说明: 使用Python中的Requests库发送"User-agent"


Rau*_*orn 5

我曾经将 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")
Run Code Online (Sandbox Code Playgroud)

编辑:

我刚刚意识到,遗憾的是,机械化仅适用于 python 2.5-2.7,但是,还有其他选项可用。请参阅为 python 3.4 安装机械化