美文网首页
python网页爬虫,实现url可访问性统计

python网页爬虫,实现url可访问性统计

作者: 沉思的雨季 | 来源:发表于2021-03-04 16:55 被阅读0次

1、程序功能设计

从txt文件中读取url,通过request对象进行访问,获取请求的响应状态,统计url访问异常的状态码、错误原因、响应时间等数据,并将异常url及异常状态打印输出。

2、技术要点

  • 解决url访问响应时间统计。
  • 解决访问异常捕获及处理。
  • 解决异常状态的输出及打印。

3、python编码实现

代码实例如下:

import urllib.request
import urllib.error
import time
import logging

###配置logging日志###
logging.basicConfig(level=logging.ERROR,
                   filename='./log.txt',
                   filemode='a',    # w:每次都会重新写 a:追加模式
                   format='%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s')

###读取URL文件,准备访问###
file = r"url.txt"     # url文本
list = []   # 定义一个空列表
error_list = set()
with open(file, 'r+', encoding='utf-8') as f:   # 将url文件读入列表
    lines = f.readlines()
    for url in lines:
        list.append(url)
print("共有{0}个url开始访问......".format(len(list)))  # 打印url的个数

for index, url1 in enumerate(list):    # 遍历索引和值
    error_code = ''
    error_reason = ''

    ###处理URL http前缀###
    if not url1.startswith("http://"):
        url2 = "http://" + url1.rstrip()
    else:
        url2 = url1.rstrip()
    print("开始第{0}个url访问:{1}".format(index+1,url2))

    try:                        # 使用try except语句避免因异常域名导致整个for大循环报错终止
        start = time.clock()
        file = urllib.request.urlopen(url2,timeout=15)
        elapsed = (time.clock() - start)        # 获取访问时长
        print("%s---->%s, 耗时%s" %(url2,file.getcode(),elapsed))
    except urllib.error.URLError as e:          # 异常域名会进入except,可以得到出错原因和出错http状态码
        print("%s异常" % url2)
        if hasattr(e, "code"):
            print("错误状态码:%s" % e.code)
            error_code = str(e.code)
        if hasattr(e, "reason"):
            print("出错原因:%s" % e.reason)
            error_reason = str(e.reason)
        error_status = error_code + '\t'+error_reason
        error_list.add(url2+'\t'+error_status+"\n")   # 将所有异常域名存入set集合,会自动去重

print("所有异常URL:")
for line in error_list:             # 循环打印
    print(line)
abnormal_list = open('异常URL列表.txt', 'w')    # 如果之前有检测记录,则直接被覆盖
abnormal_list.writelines(error_list)            # 将set的元素全部一次性写入
abnormal_list.close()                       # 关闭文件句柄

相关文章

网友评论

      本文标题:python网页爬虫,实现url可访问性统计

      本文链接:https://www.haomeiwen.com/subject/peukqltx.html