cor*_*zza 2 python web-crawler
我正在研究用Python制作的网络爬虫,我偶然发现了一个非常简单的网页爬虫.但是,我不理解最后几行,在以下代码中突出显示:
import sys
import re
import urllib2
import urlparse
tocrawl = [sys.argv[1]]
crawled = []
keywordregex = re.compile('<meta\sname=["\']keywords["\']\scontent=["\'](.*?)["\']\s/>')
linkregex = re.compile('<a\s(?:.*?\s)*?href=[\'"](.*?)[\'"].*?>')
while 1:
crawling = tocrawl.pop(0)
response = urllib2.urlopen(crawling)
msg = response.read()
keywordlist = keywordregex.findall(msg)
crawled.append(crawling)
links = linkregex.findall(msg)
url = urlparse.urlparse(crawling)
a = (links.pop(0) for _ in range(len(links))) //What does this do?
for link in a:
if link.startswith('/'):
link = 'http://' + url[1] + link
elif link.startswith('#'):
link = 'http://' + url[1] + url[2] + link
elif not link.startswith('http'):
link = 'http://' + url[1] + '/' + link
if link not in crawled:
tocrawl.append(link)
Run Code Online (Sandbox Code Playgroud)
那条线对我来说看起来像是一种列表理解,但我不确定,我需要一个解释.
它是一个生成器表达式,它只是在links迭代它时清空列表.
他们本可以取代这部分
a = (links.pop(0) for _ in range(len(links))) //What does this do?
for link in a:
Run Code Online (Sandbox Code Playgroud)
有了这个:
while links:
link = links.pop(0)
Run Code Online (Sandbox Code Playgroud)
它也会起作用.但是,由于从列表末尾弹出更有效,这将比以下任何一个更好:
links.reverse()
while links:
link = links.pop()
Run Code Online (Sandbox Code Playgroud)
当然,如果您按照相反的顺序跟踪链接(我不明白为什么需要按顺序处理),那么不反转links列表并弹出结束会更有效.