2012-04-05 3 views
3

매우 간단한 웹 크롤러를 작성하고 파일 '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입니다 :

여기 내 코드의 관련 조각입니다. 파서는 지정된 URL에있는 파일 대신 빈 'robots.txt' 파일을 읽고 모든 can_fetch() 쿼리에 True을 반환합니다. 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, hosturl 속성은 정확하지만 항목에서. '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 :. 나는이 문제를 해결 한'robots.txt' 파일을 구문 분석 this external library를 사용하여. (하지만 원래의 질문에 답하지 못했습니다!) 터미널에서 더 많은 시간을 보낸 후에는 robotparser이 과 같은 'robots.txt' 사양에 특정 추가 사항을 처리 할 수 ​​없으며 빈 줄에 문제가있는 것 같습니다. 파일을 읽어들입니다. Stack Overflow 및 Python.org (Google, YouTube 또는 내 원래 Udacity 파일은 포함하지 않음)에 Sitemap 문과 빈 줄이 포함되어 있습니다. 나보다 똑똑한 사람이 이것을 확인하거나 설명 할 수 있다면 여전히 감사 할 것입니다!

+0

그런데이 스 니펫은 관련 항목을 빠뜨린 경우를 대비하여 [여기] (https://github.com/ecmendenhall/DaveDaveFind/blob/master/crawler/udacity_crawler.py)에서 볼 수 있습니다. – ecmendenhall

+0

line print rp는 'robots.txt'파일의 내용을 인쇄해야합니다. 그 점에 대해 확실합니까? – Hoff

+0

확실합니다. 내가 링크 한 외부 예제를 사용했을 때, 이것은 어떻게 동작 하는가입니다. 경우에 따라, 나는 통역사로부터 좀 더 많은 정보를 가지고 나의 질문을 업데이트했다. URL 속성은 모두 올바르게 보이지만,'entries'는 빈리스트입니다. – ecmendenhall

답변

2

이 외부 라이브러리를 사용하여 'robots.txt'파일을 구문 분석하여이 문제를 해결했습니다. (하지만 원래의 질문에 답하지 못했습니다!) 터미널에서 더 많은 시간을 보낸 후에는 robparser가 Sitemap과 같은 'robots.txt'사양에 특정 추가 사항을 처리 할 수 ​​없으며 빈 줄에 문제가있는 것 같습니다. 파일을 읽어들입니다. 스택 오버플로 및 Python.org (Sitemap 문과 빈 줄이 포함 된 Google, YouTube 또는 원래 Udacity 파일은 제외). 나보다 똑똑한 사람이 이것을 확인하거나 설명 할 수 있다면 여전히 감사 할 것입니다!

0

용액 여기

pip install reppy 

몇 예 reppy 모듈을 사용할 수있다;

In [1]: import reppy 

In [2]: x = reppy.fetch("http://google.com/robots.txt") 

In [3]: x.atts 
Out[3]: 
{'agents': {'*': <reppy.agent at 0x1fd9610>}, 
'sitemaps': ['http://www.gstatic.com/culturalinstitute/sitemaps/www_google_com_culturalinstitute/sitemap-index.xml', 
    'http://www.google.com/hostednews/sitemap_index.xml', 
    'http://www.google.com/sitemaps_webmasters.xml', 
    'http://www.google.com/ventures/sitemap_ventures.xml', 
    'http://www.gstatic.com/dictionary/static/sitemaps/sitemap_index.xml', 
    'http://www.gstatic.com/earth/gallery/sitemaps/sitemap.xml', 
    'http://www.gstatic.com/s2/sitemaps/profiles-sitemap.xml', 
    'http://www.gstatic.com/trends/websites/sitemaps/sitemapindex.xml']} 

In [4]: x.allowed("/catalogs/about", "My_crawler") # Should return True, since it's allowed. 
Out[4]: True 

In [5]: x.allowed("/catalogs", "My_crawler") # Should return False, since it's not allowed. 
Out[5]: False 

In [7]: x.allowed("/catalogs/p?", "My_crawler") # Should return True, since it's allowed. 
Out[7]: True 

In [8]: x.refresh() # Refresh robots.txt, perhaps a magic change? 

In [9]: x.ttl 
Out[9]: 3721.3556718826294 

Voila!

관련 문제