我正在寫一個非常簡單的網絡爬蟲,並試圖解析'robots.txt'
文件。我在標準庫中找到了robotparser
模塊,應該這樣做。我正在使用Python 2.7.2。不幸的是,我的代碼不會正確加載'robots.txt'
文件,我不知道爲什麼。Python robotparser模塊不會加載'robots.txt'
這裏是我的代碼的相關片段:
from urlparse import urlparse, urljoin
import robotparser
def get_all_links(page, url):
links = []
page_url = urlparse(url)
base = page_url[0] + '://' + page_url[1]
robots_url = urljoin(base, '/robots.txt')
rp = robotparser.RobotFileParser()
rp.set_url(robots_url)
rp.read()
for link in page.find_all('a'):
link_url = link.get('href')
print "Found a link: ", link_url
if not rp.can_fetch('*', link_url):
print "Page off limits!"
pass
這裏page
是一個解析BeautifulSoup對象和url
存儲爲一個字符串的URL。解析器讀取空白的'robots.txt'
文件,而不是指定URL處的文件,並將True
返回給所有can_fetch()
查詢。它看起來好像沒有打開URL或者沒有閱讀文本文件。
我也在交互式解釋器中試過了。這是發生了什麼,使用與documentation頁面相同的語法。
Python 2.7.2 (default, Aug 18 2011, 18:04:39)
[GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import robotparser
>>> url = 'http://www.udacity-forums.com/robots.txt'
>>> rp = robotparser.RobotFileParser()
>>> rp.set_url(url)
>>> rp.read()
>>> print rp
>>>
線print rp
應該打印'robots.txt'
文件的內容,但它返回空白。更令人沮喪的是,theseexamples這兩個工作完全正常,但我嘗試自己的URL時失敗。我對Python非常陌生,我無法弄清楚發生了什麼問題。據我所知,我使用模塊的方式與文檔和示例相同。謝謝你的幫助!
更新1:這裏是解釋幾行,萬一print rp
沒有檢查是否'robots.txt'
在讀好方法的path
,host
和url
屬性是正確的,但是從條目。通過使用this external library解析'robots.txt'
文件我已經解決了這個問題:'robots.txt'
仍未讀取
>>> rp
<robotparser.RobotFileParser instance at 0x1004debd8>
>>> dir(rp)
['__doc__', '__init__', '__module__', '__str__', '_add_entry', 'allow_all', 'can_fetch', 'default_entry', 'disallow_all', 'entries', 'errcode', 'host', 'last_checked', 'modified', 'mtime', 'parse', 'path', 'read', 'set_url', 'url']
>>> rp.path
'/robots.txt'
>>> rp.host
'www.udacity-forums.com'
>>> rp.entries
[]
>>> rp.url
'http://www.udacity-forums.com/robots.txt'
>>>
更新2。 (但我還沒有回答原來的問題!)花了一些時間在終端後,我最好的猜測是robotparser
不能處理'robots.txt'
規範的某些增加,如Sitemap
,並且空白行有問題。它將從例如文件中讀取。 Stack Overflow和Python.org,但不包括Google,YouTube或我的原始Udacity文件,其中包括Sitemap
陳述和空行。如果有人比我更聰明,我仍然可以欣賞它,可以證實或解釋這一點!
順便說一句,你可以在上下文[這裏](https://github.com/ecmendenhall/DaveDaveFind/blob/master/crawler/udacity_crawler.py)中看到這段代碼,以防我遺漏了相關的東西。 – ecmendenhall 2012-04-05 10:18:47
行打印rp應該打印'robots.txt'文件的內容 - 你確定嗎? – Hoff 2012-04-05 10:40:53
很確定。當我使用我連接的外部示例時,這是它的表現。爲了以防萬一,我使用翻譯的更多信息更新了我的問題。 URL屬性都看起來正確,但是「entries」是一個空列表。 – ecmendenhall 2012-04-05 10:55:52