kyr*_*nia 1 python robots.txt web-scraping python-3.x
我正在使用robotparser
Python 中的 urlib 模块来确定是否可以下载网页。然而,当通过默认用户代理访问 robots.txt 文件时,我正在访问的一个站点会返回 403 错误,但如果通过使用我的用户代理字符串的请求下载,则会返回正确的响应。(当使用请求包默认用户代理访问时,该网站还会给出 403,表明它们只是阻止常见/通用用户代理字符串,而不是将它们添加到 robots.txt 文件中)。
无论如何,是否可以更改 rootparser 模块中的用户代理?或者,加载单独下载的 robots.txt 文件?
没有使用 User-Agent 来获取 robots.txt 的选项RobotFileParser
,但您可以自己获取它并将字符串数组路径传递给该parse()
方法:
from urllib.robotparser import RobotFileParser
import urllib.request
rp = RobotFileParser()
with urllib.request.urlopen(urllib.request.Request('http://stackoverflow.com/robots.txt',
headers={'User-Agent': 'Python'})) as response:
rp.parse(response.read().decode("utf-8").splitlines())
print(rp.can_fetch("*", "http://stackoverflow.com/posts/"))
Run Code Online (Sandbox Code Playgroud)