【发布时间】:2013-11-05 20:40:25
【问题描述】:
我正在尝试使用 python 实现网络爬虫。 这是我目前所拥有的:
import urllib2
seed=raw_input('Enter a url : ')
def getAllNewLinksOnPage(page,prevLinks):
response = urllib2.urlopen(page)
html = response.read()
links,pos,allFound=[],0,False
while not allFound:
aTag=html.find("<a href=",pos)
if aTag>-1:
href=html.find('"',aTag+1)
endHref=html.find('"',href+1)
url=html[href+1:endHref]
if url[:7]=="http://":
if url[-1]=="/":
url=url[:-1]
if not url in links and not url in prevLinks:
links.append(url)
print url
closeTag=html.find("</a>",aTag)
pos=closeTag+1
else:
allFound=True
return links
toCrawl=[seed]
crawled=[]
while toCrawl:
url=toCrawl.pop()
crawled.append(url)
newLinks=getAllNewLinksOnPage(url,crawled)
toCrawl=list(set(toCrawl)|set(newLinks))
print crawled
我想知道如何实施深度搜索并对结果进行排序。
【问题讨论】:
-
你见过scrapy吗? scrapy.org
-
如果你想自己动手学习udacity example
-
请修正缩进,并包含所有缺失的代码(如有必要)以使其成为可运行的示例,以便我们知道您缺少什么。
-
使用 HTML 解析器(如标准库中内置的解析器)或
BeautifulSoup或lxml等第三方库,解析 HTML 和查找链接要容易得多。但看起来您的getAllNewLinksOnPage不是您遇到问题的部分,对吧? -
我认为你应该首先使用xpath和lxml
标签: python python-2.7 web-crawler