【发布时间】:2015-11-08 17:19:41
【问题描述】:
我尝试使用 Python2.7 抓取整个网站:
- 我使用robotparser解析了robots.txt文件
- 我通过网站打开每个链接“a”,然后
- 我将它们添加到要抓取的页面列表中 重点是: 我试图避开 Robots.txt 文件中的所有路径,但它们仍在要抓取的页面列表中。
如何从抓取列表中删除 Robot.txt 路径?
我还没有通过 stackoverflow 找到任何帮助。
我的代码如下:
import robotparser
import urlparse
import urllib
import urllib2
from BeautifulSoup import *
AGENT_NAME = 'PYMOTW'
URL_BASE = 'website'
urls = [URL_BASE]
visited = [URL_BASE] # Create a copy
parser = robotparser.RobotFileParser()
parser.set_url(urlparse.urljoin(URL_BASE, 'robot.txt'))
parser.read()
PATHS = [
'/..../',
]
for path in PATHS:
print '%6s : %s' % (parser.can_fetch(AGENT_NAME, path), path)
url = urlparse.urljoin(URL_BASE, path)
print '%6s : %s' % (parser.can_fetch(AGENT_NAME, url), url)
robot = [url]
while (len(urls) > 0 and robot != True):
html = urllib.urlopen(urls[0]).read()
soup = BeautifulSoup(html) # Parse All HTML using BeautifulSoup
urls.pop(0)
# Retrieve all of Tags as a list
for tags in soup.findAll('a', href = True):
tags['href'] = urlparse.urljoin(URL_BASE, tags['href'])
if URL_BASE in tags['href'] and tags['href'] not in visited:
urls.append(tags['href'])
visited.append(tags['href'])
c = len(visited)
print visited
print 'page visited', c
【问题讨论】:
-
欢迎来到 Stack Overflow!我已编辑您的帖子以删除代码 sn-p 功能,该功能仅适用于在 Web 浏览器中运行的 HTML / JavaScript。除了删除 Python 3 标记外,我还修复了拼写并添加了格式以提高可读性。像这样改进您的问题将增加人们阅读您的问题并获得良好答案的机会。
-
谢谢@AnthonyGeoghegan
-
嗨@J.F.Sebastian。返回的是 True 值的列表。
-
@J.F.Sebastian - 我更正了给出网址的代码。我有禁止列表,但我不确定如何将其从列表中删除以进行抓取?
-
您的代码有点不清楚,您想获取robot.txt,并且对于您预定义的每个路径(在
PATHS),您只想在robot 允许的情况下访问该页面?
标签: python python-2.7 beautifulsoup