所以我留给这个网络爬虫的唯一问题是,当顶级域名发生变化时,比如从imdb到youtube,它会把robots.txt从imdb的不允许规则切换到youtube。我相信,只要在一开始就声明变量的方式,就可以解决所有问题。
import urllib.request
import urllib.parse
from bs4 import BeautifulSoup
import re
re.IGNORECASE = True
#SourceUrl
url = "http://www.imdb.com"
urls = [url]
visited =[url]
robotsUrl = url +'/robots.txt'
while len(urls) < 250000:
try:
htmltext = urllib.request.urlopen(urls[0]).read()
robots = urllib.request.urlopen(robotsUrl).read()
disallowList = re.findall(b'Disallow\:\s*([a-zA-Z0-9\*\-\/\_\?\.\%\:\&]+)', robots)
except:
print (urls[0])
sourceCode = BeautifulSoup(htmltext, "html.parser")
urls.pop(0)
print(len(urls))
for link in sourceCode.findAll('a', href=True):
if "http://" not in link['href']:
link['href'] = urllib.parse.urljoin(url,link['href'])
in_disallow = False
for i in range(len(disallowList)):
if (disallowList[i]).upper().decode() in link['href'].upper():
in_disallow = True
break
if not in_disallow:
if link['href'] not in visited:
urls.append(link['href'])
visited.append(link['href'])
print (visited)发布于 2015-09-10 03:01:25
只要你的robots.txt中使用的域名与你的robots.txt的url对应的域名相匹配,一切都没问题。换句话说,您可以在所有urls中将yoursite.imdb替换为yoursite.youtube。这很好。
更新
假设您在robots.txt中声明了一个sitemap,那么它应该具有相同的tld。
http://www.yoursite.imbd/robots.txt
应包含:
sitemap:http://www.yoursite.imbd/sitemap1.xml (非.youtube)
否则,对于allow或disallow之类的指令,没有影响,因为TDL不会出现在路径中。
https://stackoverflow.com/questions/32470646
复制相似问题