【问题标题】:Parsing Robots.txt in python在 python 中解析 Robots.txt
【发布时间】:2017-03-29 06:17:29
【问题描述】:

我想在 python 中解析 robots.txt 文件。 我已经探索了 robotParser 和 robotsExclusionParser,但没有什么能真正满足我的标准。我想一次性获取所有 diallowedUrls 和 allowedUrls,而不是手动检查每个 url 是否允许。有没有图书馆可以做到这一点?

【问题讨论】:

  • 请问robot.txt包含什么,解析文本文件是什么意思?
  • robots.txt 是每个站点地图支持都遵循的标准。站点地图:使我们的内容可搜索。
  • 好吧,现在更有意义了,也许你应该在你的问题中为不熟悉这个概念的其他人链接到这个。
  • 由于robot.txt数据在<pre>标签中,这里不能使用html解析,有一个备用选项disallow = [ i for i in data.split('\n') if 'Disallow' in i]

标签: python robots.txt


【解决方案1】:

为什么你必须手动检查你的网址? 您可以在 Python 3 中使用 urllib.robotparser,并执行类似的操作

import urllib.robotparser as urobot
import urllib.request
from bs4 import BeautifulSoup


url = "example.com"
rp = urobot.RobotFileParser()
rp.set_url(url + "/robots.txt")
rp.read()
if rp.can_fetch("*", url):
    site = urllib.request.urlopen(url)
    sauce = site.read()
    soup = BeautifulSoup(sauce, "html.parser")
    actual_url = site.geturl()[:site.geturl().rfind('/')]

    my_list = soup.find_all("a", href=True)
    for i in my_list:
        # rather than != "#" you can control your list before loop over it
        if i != "#":
            newurl = str(actual_url)+"/"+str(i)
            try:
                if rp.can_fetch("*", newurl):
                    site = urllib.request.urlopen(newurl)
                    # do what you want on each authorized webpage
            except:
                pass
else:
    print("cannot scrap")

【讨论】:

    【解决方案2】:

    您可以使用curl 命令将robots.txt 文件读取为单个字符串,并通过换行检查允许和禁止URL 将其拆分。

    import os
    result = os.popen("curl https://fortune.com/robots.txt").read()
    result_data_set = {"Disallowed":[], "Allowed":[]}
    
    for line in result.split("\n"):
        if line.startswith('Allow'):    # this is for allowed url
            result_data_set["Allowed"].append(line.split(': ')[1].split(' ')[0])    # to neglect the comments or other junk info
        elif line.startswith('Disallow'):    # this is for disallowed url
            result_data_set["Disallowed"].append(line.split(': ')[1].split(' ')[0])    # to neglect the comments or other junk info
    
    print (result_data_set)
    

    【讨论】:

    • 不客气。不@Ritu,找不到满足您的用例的。也许您可以扩展它并构建库。
    猜你喜欢
    • 1970-01-01
    • 2017-05-18
    • 2012-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-27
    • 2018-01-27
    相关资源
    最近更新 更多