Introducción a la biblioteca de Python Pycurl

Pycurl puede devolver información relacionada con la web, como:

Código de estado HTTPS: 200
Tiempo de resolución de DNS: 76,67 ms
Tiempo de establecimiento de la conexión: 107,84 ms Tiempo de
transmisión de preparación: 158,23 ms Tiempo de
inicio de la transmisión: 185,80 ms Tiempo de
finalización de la transmisión: 188,38 ms
Tamaño del paquete de descarga: 6709 bytes / s
Tamaño del encabezado HTTP:
Velocidad de descarga media de 341 bytes : 35686 bytes / s

1.curlwebinfo.py

Obtener información de acceso a la web

import pycurl as pycurl
import os
import certifi

# 创建一个空列表,用于保存url地址
url_list = []

# 创建一个空列表,用于保存url地址探测信息
url_list_check_info = []

class CurlWebInfo(object):
    def __init__(self):
        pass
        # self.curl_web_info()

    def add_url_list(self):
        # 1.打开文件(文件名区分大小写)
        file = open("url_list")

        # 2.读取文件
        # 使用readline函数实现逐行读取
        # 避免文件全部加载进入内存造成内存资源紧缺,且有可能使程序崩溃
        while True:
            url = file.readline()
            # 判断是否可以读取到内容
            if not url:
                return
            url_list.append(url.strip())  # 删除首尾空白
        # 3.关闭文件
        file.close()
        pass

    def curl_web_info(self):
        for url in url_list:
            """设置默认值"""
            namelookup_time = "-100"  # 获取DNS解析时间
            connect_time = "-100"  # 获取建立连接时间
            pretransfer_time = "-100"  # 获取从建立连接到准备传输所消耗的时间
            starttransfer_time = "-100"  # 获取从建立连接到传输开所消耗的时间
            toltal_time = "-100"  # 获取传输的总时间
            http_code = "-100"  # 获取HTTP状态码
            size_downloao = "-100"  # 获取下载数据包大小
            header_size = "-100"  # 获取HTTP头部大小
            speed_download = "-100"  # 获取平均下载速度
            curl_status = 1  # 设置连接状态码

            URL = url  # 探测对象
            c = pycurl.Curl()  # 创建一个Curl对象
            c.setopt(pycurl.SSL_VERIFYPEER, 0)  # 跳过https证书检查
            c.setopt(pycurl.URL, URL)  # 定义请求的URL常量
            c.setopt(pycurl.CONNECTTIMEOUT, 5)  # 定义请求连接的等待时间
            c.setopt(pycurl.TIMEOUT, 5)  # 定义请求超时时间
            c.setopt(pycurl.NOPROGRESS, 1)  # 屏蔽下载进度条
            c.setopt(pycurl.FORBID_REUSE, 1)  # 完成交互后强制断开连接,不重用
            c.setopt(pycurl.MAXREDIRS, 1)  # 指定HTTP重定向的最大数为1
            c.setopt(pycurl.DNS_CACHE_TIMEOUT, 30)  # 设置保存DNS信息的时间为30秒

            # 创建一个文件对象,以”wb”方式打开,用来存储返回的http头部及页面内容
            indexfile = open(os.path.dirname(os.path.realpath(__file__)) + "/content.txt", "wb")

            # 将返回的HTTP HEADER定向到 indexfile文件对象
            c.setopt(pycurl.WRITEHEADER, indexfile)

            # 将返回的HTML内容定向到indexfile文件对象
            c.setopt(pycurl.WRITEDATA, indexfile)

            try:
                c.perform()  # 提交请求
            except Exception as e:
                print("connecion error: %s " % str(e))
                indexfile.close()
                c.close()

            try:
                namelookup_time = c.getinfo(c.NAMELOOKUP_TIME)  # 获取DNS解析时间
                connect_time = c.getinfo(c.CONNECT_TIME)  # 获取建立连接时间
                pretransfer_time = c.getinfo(c.PRETRANSFER_TIME)  # 获取从建立连接到准备传输所消耗的时间
                starttransfer_time = c.getinfo(c.STARTTRANSFER_TIME)  # 获取从建立连接到传输开所消耗的时间
                toltal_time = c.getinfo(c.TOTAL_TIME)  # 获取传输的总时间
                http_code = c.getinfo(c.HTTP_CODE)  # 获取HTTP状态码
                size_downloao = c.getinfo(c.SIZE_DOWNLOAD)  # 获取下载数据包大小
                header_size = c.getinfo(c.HEADER_SIZE)  # 获取HTTP头部大小
                speed_download = c.getinfo(c.SPEED_DOWNLOAD)  # 获取平均下载速度
            except Exception as e:
                # 出错后的处理代码
                print("(未知错误")
                # 修改状态码
                curl_status = -1
            finally:
                print("123456")

            curl_web_info = {
                'http_code': http_code,
                'namelookup_time': namelookup_time,
                'connect_time': connect_time,
                'pretransfer_time': pretransfer_time,
                'starttransfer_time': starttransfer_time,
                'size_downloao': size_downloao,
                'header_size': header_size,
                'speed_download': speed_download,
                'toltal_time': toltal_time,
                'url': URL,
                'curl_status': curl_status
            }
            # 将探测信息写入列表中
            url_list_check_info.append(curl_web_info)

            # 关闭文件及Curl对象
            indexfile.close()
            c.close()

    # 返回探测列表
    def return_url_list_check_info(self):
        msg = CurlWebInfo()
        msg.add_url_list()
        msg.curl_web_info()
        return url_list_check_info

if __name__ == '__main__':
    test = CurlWebInfo()
    list = []
    list = test.return_url_list_check_info()
    for webibfo_list in list:
        if webibfo_list is not None:
            print(webibfo_list)
        else:
            break

2.application.py

Salida de información de acceso web

import smtplib
import curlwebinfo
from email.mime.text import MIMEText
from email.header import Header

# 创建CurlWebInfo实例
CURL_WEB_INFO = curlwebinfo.CurlWebInfo

# 创建一个空字典,存储所有采集信息
receiver_url_list_check_info = []

"""
使用的元素有:

"""

# 打印输出相关数据
# sendEmail

# web探测
def receiver_curl_web_info():
    curl_web_info = CURL_WEB_INFO.return_url_list_check_info(self=True)
    if curl_web_info:
        receiver_url_list_check_info = curl_web_info
    else:
        return
    # 遍历列表
    for info in receiver_url_list_check_info:
        print(info)

# 程序启动入口
if __name__ == '__main__':
    receiver_curl_web_info()

3.url_list

https://www.baidu.com
......

4. Date cuenta del efecto

{'http_code': '-100', 'namelookup_time': '-100', 'connect_time': '-100', 'pretransfer_time': '-100', 'starttransfer_time': '-100', 'size_downloao': '-100', 'header_size': '-100', 'speed_download': '-100', 'toltal_time': '-100', 'url': 'https://www.baidu.coss', 'curl_status': -1}
{'http_code': 200, 'namelookup_time': 0.008825, 'connect_time': 0.039627, 'pretransfer_time': 0.078427, 'starttransfer_time': 0.096421, 'size_downloao': 227.0, 'header_size': 879, 'speed_download': 2364.0, 'toltal_time': 0.096446, 'url': 'https://www.baidu.com', 'curl_status': 1}
{'http_code': 200, 'namelookup_time': 0.008211, 'connect_time': 0.039058, 'pretransfer_time': 0.061932, 'starttransfer_time': 0.084628, 'size_downloao': 984.0, 'header_size': 271, 'speed_download': 11714.0, 'toltal_time': 0.084652, 'url': 'xxx', 'curl_status': 1}
{'http_code': 200, 'namelookup_time': 0.045153, 'connect_time': 0.075333, 'pretransfer_time': 0.097549, 'starttransfer_time': 0.123353, 'size_downloao': 5176.0, 'header_size': 296, 'speed_download': 42081.0, 'toltal_time': 0.123378, 'url': 'xxx', 'curl_status': 1}
{'http_code': 301, 'namelookup_time': 0.005891, 'connect_time': 0.035221, 'pretransfer_time': 0.035542, 'starttransfer_time': 0.054511, 'size_downloao': 162.0, 'header_size': 251, 'speed_download': 3000.0, 'toltal_time': 0.054537, 'url': 'xxx', 'curl_status': 1}
{'http_code': 200, 'namelookup_time': 0.005009, 'connect_time': 0.031912, 'pretransfer_time': 0.051745, 'starttransfer_time': 0.090513, 'size_downloao': 12978.0, 'header_size': 297, 'speed_download': 144200.0, 'toltal_time': 0.090659, 'url': 'xxx', 'curl_status': 1}

Supongo que te gusta

Origin blog.51cto.com/14539398/2677478
Recomendado
Clasificación