首页 > 解决方案 > 在 python 中解析 Robots.txt 并检查 http 状态码

问题描述

我在 python 中解析 robots.txt 时遇到一些问题。我想将 robots.txt 的每一行存储在一个数组中,该数组目前正在工作。

之后我想检查 url 和数组中的每个值(这将是一个唯一的 URL),当我请求页面时我收到了哪些状态代码。例如,我们在数组中有值“/abc”,url 是“ https://stackoverflow.com ”。然后,我想检查 http 状态代码的 URL“ https://stackoverflow.com/abc ”并将其打印出来。

到目前为止我得到的代码是:

import os
import os
import io
import urllib.request
import urllib.parse
import urllib.error



#Command to Use User Input as URL:
#url = input("Input Url" + '\n')

url = 'https://stackoverflow.com/robots.txt'
raw_robots = urllib.request.urlopen(url)
robots= raw_robots.read().decode('utf-8')
result_data_set = {"Disallowed":[], "Allowed":[]}

for line in robots.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)

url2 = 'https://stackoverflow.com'

for x in result_data_set:
    try:
        conn = urllib.request.urlopen(url2+x)
    except urllib.error.HTTPError as e:
    # Return code error (e.g. 404, 501, ...)
    # ...
        print('HTTPError: {}'.format(e.code))
    except urllib.error.URLError as e:
    # Not an HTTP-specific error (e.g. connection refused)
    # ...
        print('URLError: {}'.format(e.reason))
    else:
    # 200
    # ...
        print(x+'good')

将不胜感激任何帮助。

标签: pythonpython-3.x

解决方案


推荐阅读