python - 在 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')
将不胜感激任何帮助。
解决方案
推荐阅读
- java - 为什么要在对象数组类内部创建对象数组?
- opengl - 有选择地绘制到着色器中的某些输出
- laravel - laravel 关系 belongsTo 和方法 with
- reinforcement-learning - Q 学习和神经网络的问题
- excel - 循环中的 If-Else-Statement
- python - 如何在此 LSTM 示例代码中计算可训练参数数量为 335872?
- jquery - 阴影行切换有/没有 jquery / css 未应用于第 n 行
- mysql - MYSQL - 在 select 和 group by 中将多列显示为不同的值
- c# - 从 .net core 中的其他类库访问 automapper
- flutter - Flutter 文本在某些情况下无法正确呈现