2017-04-16 7 views
1

我是卡內基梅隆大學的一年級學生,他在第一學期項目中完全失敗。使用美麗湯的請求被阻止

當我用美麗的湯作出要求時,我被封鎖爲一個「機器人」。

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的消息說他們懷疑我是一個機器人。

  1. 通過美麗的湯有什麼可能的解決方案? (我曾嘗試Scrapy使用它的Crawlera,但由於缺乏Python知識,我無法使用它)。我不介意它是否爲付費服務,只要它對於初學者來說足夠「直觀」即可使用。

我真的很感激你的幫助。

真誠,

艾薩克李

回答

1

被阻止爲機器人可能有各種原因。

由於您「按原樣」使用請求庫,該塊最可能的原因是缺少User Agent標頭。

針對機器人和抓取的第一道防線是檢查來自其中一個主要瀏覽器的用戶代理標題並阻止所有非瀏覽器用戶代理。

短版:試試這個:

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

+0

非常感謝!有效! – Isaac

+0

不客氣:-) – rrschmidt

0

我用機械化爲這樣的東西,它一直是幾年,但它應該仍然工作。

嘗試是這樣的:

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") 

編輯:

我剛剛意識到,可悲的是,機械化僅供巨蟒2.5-2.7 availble的,但是也有其他可供選擇。請參閱Installing mechanize for python 3.4

+0

感謝Raudbjorn!這對Python 3不起作用,是嗎? – Isaac

+0

不,對不起,請參閱我編輯的答案。 但其他庫允許您添加標題並關閉機器人處理;請記住,節流一下可能是個好主意,或者您可能會「被抓到」,請在每次請求後使用time.sleep(1)以避免被識別爲bot。 – Raudbjorn

+0

非常感謝! – Isaac