【发布时间】:2012-05-27 14:48:23
【问题描述】:
我正在做一个爬虫项目。我陷入了这样一种情况,即页面上的 href 文本在该域下的其他页面上不断重复。 例如,如果 url 是 example.com,那么这些页面上的 href 值为 hrefList=[/hello/world,/aboutus,/blog,/contact]。
所以这些页面的网址是 example.com/hello/world example.com/aboutus 等等
现在在 example.com/hello/world 页面上,hrefList 再次出现。因此我会得到网址 example.com/hello/world/hello/world, example.com/hello/world/aboutus 等
现在在这些页面中,/hello/world/hello/world 是一个正确的页面,其 http 状态为 200,并且正在递归地发生。其余页面将找不到页面,因此可以丢弃
我正在获取不正确网址的新网址列表。有什么办法可以克服吗?
这是我的代码库:
for url in allUrls:
if url not in visitedUrls:
visitedUrls.append(url)
http=httplib2.Http()
response,content=http.request(url,headers={'User-Agent':'Crawler-Project'})
if (response.status/100<4):
soup=BeautifulSoup(content)
links=soup.findAll('a',href=True)
for link in links:
if link.has_key('href'):
if len(link['href']) > 1:
if not any(x in link['href'] for x in ignoreUrls):
if link['href'][0]!="#":
if "http" in link["href"]:
allUrls.append(link["href"])
else:
if url[-1]=="/" and link['href'][0]=="/":
allUrls.append(url+link['href'][1:])
else:
if not (url[-1] =="/" or link['href'][0] =="/"):
allUrls.append(url+"/"+link['href'])
else:
allUrls.append(url+link['href'])
【问题讨论】:
-
如果 href 是 "/hello/world" 那么它是绝对的,你不应该将它添加到字符串的末尾。如果它是相对的,那么页面没有正确完成,你注定要实施一种解决方法。问题是,为什么其中一个页面总是得到 200 OK 并且其内容每次都一样?
-
一些重构(想想函数)可以为可读性创造奇迹。神圣的 11 级缩进蝙蝠侠!
-
任何有
if some_condition+ 缩进代码的地方,您都可以将其更改为if not some_condition: continue,这样您就可以保持相同的缩进级别。 -
@Toote 据我了解,该页面未正确完成。它实际上有一个忘记密码的链接,就像一个 div,不管 /hello/world 之后出现什么。
-
@StevenRumbalski 感谢您对代码的反馈,不胜感激。
标签: python web-crawler beautifulsoup