我有一个基本的循环来查找我用urllib2.urlopen检索到的页面上的链接,但是我试图只关注页面上的内部链接..
如何使我的下面的循环只获得位于同一域的链接?
for tag in soupan.findAll('a', attrs={'href': re.compile("^http://")}):
webpage = urllib2.urlopen(tag['href']).read()
print 'Deep crawl ----> ' +str(tag['href'])
try:
code-to-look-for-some-data...
except Exception, e:
print e
答案 0 :(得分:2)
>>> import urllib
>>> print urllib.splithost.__doc__
splithost('//host[:port]/path') --> 'host[:port]', '/path'.
如果主机相同或主机为空(用于相对路径),则url属于同一主机。
for tag in soupan.findAll('a', attrs={'href': re.compile("^http://")}):
href = tag['href']
protocol, url = urllib.splittype(href) # 'http://www.xxx.de/3/4/5' => ('http', '//www.xxx.de/3/4/5')
host, path = urllib.splithost(url) # '//www.xxx.de/3/4/5' => ('www.xxx.de', '/3/4/5')
if host.lower() != theHostToCrawl and host != '':
continue
webpage = urllib2.urlopen(href).read()
print 'Deep crawl ----> ' +str(tag['href'])
try:
code-to-look-for-some-data...
except:
import traceback
traceback.print_exc()
因为你这样做
'href': re.compile("^http://")
不会使用相对路径。 就像
<a href="/folder/file.htm"></a>
也许根本不使用re?
答案 1 :(得分:0)
针对您的抓取工具的一些建议:将机械化与BeautifulSoup结合使用,这将简化您的任务。