iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >Python怎么使用Asyncio实现检查网站状态
  • 130
分享到

Python怎么使用Asyncio实现检查网站状态

2023-07-05 19:07:58 130人浏览 八月长安

Python 官方文档:入门教程 => 点击学习

摘要

这篇文章主要介绍了python怎么使用Asyncio实现检查网站状态的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇Python怎么使用Asyncio实现检查网站状态文章都会有所收获,下面我们一起来看看吧。我们可

这篇文章主要介绍了python怎么使用Asyncio实现检查网站状态的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇Python怎么使用Asyncio实现检查网站状态文章都会有所收获,下面我们一起来看看吧。

我们可以通过打开流并写入和读取 Http 请求和响应来使用 asyncio 查询网站的 HTTP 状态。

然后我们可以使用 asyncio 并发查询多个网站的状态,甚至动态报告结果。

1. 如何使用 Asyncio 检查 HTTP 状态

asyncio 模块提供了对打开套接字连接和通过流读写数据的支持。我们可以使用此功能来检查网页的状态。

这可能涉及四个步骤,它们是:

  • 打开一个连接

  • 写一个请求

  • 读取响应

  • 关闭连接

2. 打开 HTTP 连接

可以使用 asyncio.open_connection() 函数在 asyncio 中打开连接。在众多参数中,该函数采用字符串主机名和整数端口号。

这是一个必须等待的协程,它返回一个 StreamReader 和一个 StreamWriter,用于使用套接字进行读写。

这可用于在端口 80 上打开 HTTP 连接。

...# open a Socket connectionreader, writer = await asyncio.open_connection('www.Google.com', 80)

我们还可以使用 ssl=True 参数打开 SSL 连接。这可用于在端口 443 上打开 https 连接。

...# open a socket connectionreader, writer = await asyncio.open_connection('www.google.com', 443)

3. 写入 HTTP 请求

打开后,我们可以向 StreamWriter 写入查询以发出 HTTP 请求。例如,HTTP 版本 1.1 请求是纯文本格式的。我们可以请求文件路径“/”,它可能如下所示:

GET / HTTP/1.1Host: www.google.com

重要的是,每行末尾必须有一个回车和一个换行符(\r\n),末尾有一个空行。

作为 Python 字符串,这可能如下所示:

'GET / HTTP/1.1\r\n''Host: www.google.com\r\n''\r\n'

在写入 StreamWriter 之前,此字符串必须编码为字节。这可以通过对字符串本身使用 encode() 方法来实现。默认的“utf-8”编码可能就足够了。

...# encode string as bytesbyte_data = string.encode()

然后可以通过 StreamWriter 的 write() 方法将字节写入套接字。

...# write query to socketwriter.write(byte_data)

写入请求后,最好等待字节数据发送完毕并等待套接字准备就绪。这可以通过 drain() 方法来实现。这是一个必须等待的协程。

...# wait for the socket to be ready.await writer.drain()

4. 读取 HTTP 响应

发出 HTTP 请求后,我们可以读取响应。这可以通过套接字的 StreamReader 来实现。可以使用读取一大块字节的 read() 方法或读取一行字节的 readline() 方法来读取响应。

我们可能更喜欢 readline() 方法,因为我们使用的是基于文本的 HTTP 协议,它一次发送一行 html 数据。readline() 方法是协程,必须等待。

...# read one line of responseline_bytes = await reader.readline()

HTTP 1.1 响应由两部分组成,一个由空行分隔的标头,然后是一个空行终止的主体。header 包含有关请求是否成功以及将发送什么类型的文件的信息,body 包含文件的内容,例如 HTML 网页。

HTTP 标头的第一行包含服务器上所请求页面的 HTTP 状态。每行都必须从字节解码为字符串。

这可以通过对字节数据使用 decode() 方法来实现。同样,默认编码为“utf_8”。

...# decode bytes into a stringline_data = line_bytes.decode()

5. 关闭 HTTP 连接

我们可以通过关闭 StreamWriter 来关闭套接字连接。这可以通过调用 close() 方法来实现。

...# close the connectionwriter.close()

这不会阻塞并且可能不会立即关闭套接字。现在我们知道如何使用 asyncio 发出 HTTP 请求和读取响应,让我们看一些检查网页状态的示例。

6. 顺序检查 HTTP 状态的示例

我们可以开发一个示例来使用 asyncio 检查多个网站的 HTTP 状态。

在此示例中,我们将首先开发一个协程来检查给定 URL 的状态。然后我们将为排名前 10 的网站中的每一个调用一次这个协程。

首先,我们可以定义一个协程,它将接受一个 URL 字符串并返回 HTTP 状态。

# get the HTTP/S status of a WEBpageasync def get_status(url):# ...

必须将 URL 解析为其组成部分。我们在发出 HTTP 请求时需要主机名和文件路径。我们还需要知道 URL 方案(HTTP 或 HTTPS)以确定是否需要 SSL。

这可以使用 urllib.parse.urlsplit() 函数来实现,该函数接受一个 URL 字符串并返回所有 URL 元素的命名元组。

...# split the url into componentsurl_parsed = urlsplit(url)

然后我们可以打开基于 URL 方案的 HTTP 连接并使用 URL 主机名。

...# open the connectionif url_parsed.scheme == 'https':    reader, writer = await asyncio.open_connection(url_parsed.hostname, 443, ssl=True)else:    reader, writer = await asyncio.open_connection(url_parsed.hostname, 80)

接下来,我们可以使用主机名和文件路径创建 HTTP GET 请求,并使用 StreamWriter 将编码字节写入套接字。

...# send GET requestquery = f'GET {url_parsed.path} HTTP/1.1\r\nHost: {url_parsed.hostname}\r\n\r\n'# write query to socketwriter.write(query.encode())# wait for the bytes to be written to the socketawait writer.drain()

接下来,我们可以读取 HTTP 响应。我们只需要包含 HTTP 状态的响应的第一行。

...# read the single line responseresponse = await reader.readline()

然后可以关闭连接。

...# close the connectionwriter.close()

最后,我们可以解码从服务器读取的字节、远程尾随空白,并返回 HTTP 状态。

...# decode and strip white spacestatus = response.decode().strip()# return the responsereturn status

将它们结合在一起,下面列出了完整的 get_status() 协程。它没有任何错误处理,例如无法访问主机或响应缓慢的情况。这些添加将为读者提供一个很好的扩展。

# get the HTTP/S status of a webpageasync def get_status(url):    # split the url into components    url_parsed = urlsplit(url)    # open the connection    if url_parsed.scheme == 'https':        reader, writer = await asyncio.open_connection(url_parsed.hostname, 443, ssl=True)    else:        reader, writer = await asyncio.open_connection(url_parsed.hostname, 80)    # send GET request    query = f'GET {url_parsed.path} HTTP/1.1\r\nHost: {url_parsed.hostname}\r\n\r\n'    # write query to socket    writer.write(query.encode())    # wait for the bytes to be written to the socket    await writer.drain()    # read the single line response    response = await reader.readline()    # close the connection    writer.close()    # decode and strip white space    status = response.decode().strip()    # return the response    return status

接下来,我们可以为我们要检查的多个网页或网站调用 get_status() 协程。在这种情况下,我们将定义一个世界排名前 10 的网页列表。

...# list of top 10 websites to checksites = ['https://www.google.com/',    'https://www.youtube.com/',    'https://www.facebook.com/',    'https://twitter.com/',    'https://www.instagram.com/',    'https://www.baidu.com/',    'https://www.wikipedia.org/',    'https://yandex.ru/',    'https://yahoo.com/',    'https://www.whatsapp.com/'    ]

然后我们可以使用我们的 get_status() 协程依次查询每个。在这种情况下,我们将在一个循环中按顺序这样做,并依次报告每个状态。

...# check the status of all websitesfor url in sites:    # get the status for the url    status = await get_status(url)    # report the url and its status    print(f'{url:30}:\t{status}')

在使用 asyncio 时,我们可以做得比顺序更好,但这提供了一个很好的起点,我们可以在以后进行改进。将它们结合在一起,main() 协程查询前 10 个网站的状态。

# main coroutineasync def main():    # list of top 10 websites to check    sites = ['https://www.google.com/',        'https://www.youtube.com/',        'https://www.facebook.com/',        'https://twitter.com/',        'https://www.instagram.com/',        'https://www.baidu.com/',        'https://www.wikipedia.org/',        'https://yandex.ru/',        'https://yahoo.com/',        'https://www.whatsapp.com/'        ]    # check the status of all websites    for url in sites:        # get the status for the url        status = await get_status(url)        # report the url and its status        print(f'{url:30}:\t{status}')

最后,我们可以创建 main() 协程并将其用作 asyncio 程序的入口点。

...# run the asyncio programasyncio.run(main())

将它们结合在一起,下面列出了完整的示例。

# SuperFastPython.com# check the status of many webpagesimport asynciofrom urllib.parse import urlsplit # get the HTTP/S status of a webpageasync def get_status(url):    # split the url into components    url_parsed = urlsplit(url)    # open the connection    if url_parsed.scheme == 'https':        reader, writer = await asyncio.open_connection(url_parsed.hostname, 443, ssl=True)    else:        reader, writer = await asyncio.open_connection(url_parsed.hostname, 80)    # send GET request    query = f'GET {url_parsed.path} HTTP/1.1\r\nHost: {url_parsed.hostname}\r\n\r\n'    # write query to socket    writer.write(query.encode())    # wait for the bytes to be written to the socket    await writer.drain()    # read the single line response    response = await reader.readline()    # close the connection    writer.close()    # decode and strip white space    status = response.decode().strip()    # return the response    return status # main coroutineasync def main():    # list of top 10 websites to check    sites = ['https://www.google.com/',        'https://www.youtube.com/',        'https://www.facebook.com/',        'https://twitter.com/',        'https://www.instagram.com/',        'https://www.baidu.com/',        'https://www.wikipedia.org/',        'https://yandex.ru/',        'https://yahoo.com/',        'https://www.whatsapp.com/'        ]    # check the status of all websites    for url in sites:        # get the status for the url        status = await get_status(url)        # report the url and its status        print(f'{url:30}:\t{status}') # run the asyncio programasyncio.run(main())

运行示例首先创建 main() 协程并将其用作程序的入口点。main() 协程运行,定义前 10 个网站的列表。然后顺序遍历网站列表。 main()协程挂起调用get_status()协程查询一个网站的状态。

get_status() 协程运行、解析 URL 并打开连接。它构造一个 HTTP GET 查询并将其写入主机。读取、解码并返回响应。main() 协程恢复并报告 URL 的 HTTP 状态。

对列表中的每个 URL 重复此操作。该程序大约需要 5.6 秒才能完成,或者平均每个 URL 大约需要半秒。这突出了我们如何使用 asyncio 来查询网页的 HTTP 状态。

尽管如此,它并没有充分利用 asyncio 来并发执行任务。

https://www.google.com/       :    HTTP/1.1 200 OK
https://www.youtube.com/      :    HTTP/1.1 200 OK
https://www.facebook.com/     :    HTTP/1.1 302 Found
https://twitter.com/          :    HTTP/1.1 200 OK
https://www.instagram.com/    :    HTTP/1.1 200 OK
https://www.baidu.com/        :    HTTP/1.1 200 OK
https://www.wikipedia.org/    :    HTTP/1.1 200 OK
https://yandex.ru/            :    HTTP/1.1 302 Moved temporarily
https://yahoo.com/            :    HTTP/1.1 301 Moved Permanently
https://www.whatsapp.com/     :    HTTP/1.1 302 Found

7. 并发查看网站状态示例

asyncio 的一个好处是我们可以同时执行许多协程。我们可以使用 asyncio.gather() 函数在 asyncio 中并发查询网站的状态。

此函数采用一个或多个协程,暂停执行提供的协程,并将每个协程的结果作为可迭代对象返回。然后我们可以遍历 URL 列表和可迭代的协程返回值并报告结果。

这可能是比上述方法更简单的方法。首先,我们可以创建一个协程列表。

...# create all coroutine requestscoros = [get_status(url) for url in sites]

接下来,我们可以执行协程并使用 asyncio.gather() 获取可迭代的结果。

请注意,我们不能直接提供协程列表,而是必须将列表解压缩为单独的表达式,这些表达式作为位置参数提供给函数。

...# execute all coroutines and waitresults = await asyncio.gather(*coros)

这将同时执行所有协程并检索它们的结果。然后我们可以遍历 URL 列表和返回状态并依次报告每个。

...# process all resultsfor url, status in zip(sites, results):    # report status    print(f'{url:30}:\t{status}')

将它们结合在一起,下面列出了完整的示例。

# SuperFastPython.com# check the status of many webpagesimport asynciofrom urllib.parse import urlsplit # get the HTTP/S status of a webpageasync def get_status(url):    # split the url into components    url_parsed = urlsplit(url)    # open the connection    if url_parsed.scheme == 'https':        reader, writer = await asyncio.open_connection(url_parsed.hostname, 443, ssl=True)    else:        reader, writer = await asyncio.open_connection(url_parsed.hostname, 80)    # send GET request    query = f'GET {url_parsed.path} HTTP/1.1\r\nHost: {url_parsed.hostname}\r\n\r\n'    # write query to socket    writer.write(query.encode())    # wait for the bytes to be written to the socket    await writer.drain()    # read the single line response    response = await reader.readline()    # close the connection    writer.close()    # decode and strip white space    status = response.decode().strip()    # return the response    return status # main coroutineasync def main():    # list of top 10 websites to check    sites = ['https://www.google.com/',        'https://www.youtube.com/',        'https://www.facebook.com/',        'https://twitter.com/',        'https://www.instagram.com/',        'https://www.baidu.com/',        'https://www.wikipedia.org/',        'https://yandex.ru/',        'https://yahoo.com/',        'https://www.whatsapp.com/'        ]    # create all coroutine requests    coros = [get_status(url) for url in sites]    # execute all coroutines and wait    results = await asyncio.gather(*coros)    # process all results    for url, status in zip(sites, results):        # report status        print(f'{url:30}:\t{status}') # run the asyncio programasyncio.run(main())

运行该示例会像以前一样执行 main() 协程。在这种情况下,协程列表是在列表理解中创建的。

然后调用 asyncio.gather() 函数,传递协程并挂起 main() 协程,直到它们全部完成。协程执行,同时查询每个网站并返回它们的状态。

main() 协程恢复并接收可迭代的状态值。然后使用 zip() 内置函数遍历此可迭代对象和 URL 列表,并报告状态。

这突出了一种更简单的方法来同时执行协程并在所有任务完成后报告结果。它也比上面的顺序版本更快,在我的系统上完成大约 1.4 秒。

https://www.google.com/       :    HTTP/1.1 200 OK
https://www.youtube.com/      :    HTTP/1.1 200 OK
https://www.facebook.com/     :    HTTP/1.1 302 Found
https://twitter.com/          :    HTTP/1.1 200 OK
https://www.instagram.com/    :    HTTP/1.1 200 OK
https://www.baidu.com/        :    HTTP/1.1 200 OK
https://www.wikipedia.org/    :    HTTP/1.1 200 OK
https://yandex.ru/            :    HTTP/1.1 302 Moved temporarily
https://yahoo.com/            :    HTTP/1.1 301 Moved Permanently
https://www.whatsapp.com/     :    HTTP/1.1 302 Found

关于“Python怎么使用Asyncio实现检查网站状态”这篇文章的内容就介绍到这里,感谢各位的阅读!相信大家对“Python怎么使用Asyncio实现检查网站状态”知识都有一定的了解,大家如果还想学习更多知识,欢迎关注编程网Python频道。

--结束END--

本文标题: Python怎么使用Asyncio实现检查网站状态

本文链接: https://www.lsjlt.com/news/354655.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • Python怎么使用Asyncio实现检查网站状态
    这篇文章主要介绍了Python怎么使用Asyncio实现检查网站状态的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇Python怎么使用Asyncio实现检查网站状态文章都会有所收获,下面我们一起来看看吧。我们可...
    99+
    2023-07-05
  • 怎么检查linux的网络状态
    本篇内容介绍了“怎么检查linux的网络状态”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!一、通过定时收发email检测网络连通性代码如下:...
    99+
    2023-06-09
  • linux网络连接状态怎么检查
    要检查Linux系统中的网络连接状态,可以使用以下命令: ifconfig:显示当前网络接口的配置和状态,包括IP地址、网络掩码、...
    99+
    2024-02-29
    linux
  • 使用phonegap怎么检测网络的状态
    使用phonegap怎么检测网络的状态?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。实例如下:<!DOCTYPE html> <html&...
    99+
    2023-06-09
  • Linux下怎么用netstat查看网络状态、端口状态
    这篇文章给大家分享的是有关Linux下怎么用netstat查看网络状态、端口状态的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。      netstat命令是一个监控TCP...
    99+
    2023-06-04
  • Python 中怎么使用Asyncio实现异步编程
    Python 中怎么使用Asyncio实现异步编程,针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。异步是怎么一回事在传统的顺序编程中, 所有发送给解释器的指令会一条条被执行。...
    99+
    2023-06-17
  • 怎么检查Linux的内存使用状况
    要检查Linux系统的内存使用状况,可以使用以下几种方法: 使用free命令:在终端中输入free命令可以查看系统的内存使用情况...
    99+
    2024-04-02
  • 怎么使用jQuery实现发布的状态
    这篇文章主要介绍了怎么使用jQuery实现发布的状态的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇怎么使用jQuery实现发布的状态文章都会有所收获,下面我们一起来看看吧。首先,让我们考虑一个需求。我们需要一个...
    99+
    2023-07-06
  • python中怎么使用__iter__()展现外部状态
    这篇文章主要介绍python中怎么使用__iter__()展现外部状态,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!python的数据类型有哪些python的数据类型:1. 数字类型,包括int(整型)、long(长...
    99+
    2023-06-14
  • Python怎么使用描述符实现属性类型检查
    这篇“Python怎么使用描述符实现属性类型检查”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇“Python怎么使用描述符实现...
    99+
    2023-06-30
  • Python中怎么利用Asyncio实现异步编程
    本篇文章为大家展示了Python中怎么利用Asyncio实现异步编程,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。异步是怎么一回事在传统的顺序编程中, 所有发送给解释器的指令会一条条被执行。此类代码...
    99+
    2023-06-17
  • 浅析怎么使用PHP查询HTTP状态码
    PHP是一种流行的编程语言,它被广泛用于构建动态网站和Web应用程序。在Web开发过程中,我们经常需要查询HTTP状态码,以了解Web服务器返回的响应状态。本文将介绍如何使用PHP查询HTTP状态码。第一步:使用PHP构建HTTP请求要查询...
    99+
    2023-05-14
  • 怎么使用Python+tkinter实现网站下载工具
    今天小编给大家分享一下怎么使用Python+tkinter实现网站下载工具的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家参考一下,希望大家阅读完这篇文章后有所收获,下面我们一起来了解一下吧。开发...
    99+
    2023-07-05
  • 怎么在python中利用asyncio实现异步IO
    这篇文章给大家介绍怎么在python中利用asyncio实现异步IO,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。Python主要用来做什么Python主要应用于:1、Web开发;2、数据科学研究;3、网络爬虫;4、嵌...
    99+
    2023-06-14
  • 怎么使用sestatus命令查看SESELinux当前状态
    这篇文章主要为大家展示了“怎么使用sestatus命令查看SESELinux当前状态”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下“怎么使用sestatus命令查看SESELinux当前状态”这篇...
    99+
    2023-06-28
  • 怎么使用Laravel和SSR实现保存登录状态
    这篇“怎么使用Laravel和SSR实现保存登录状态”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇“怎么使用Laravel和S...
    99+
    2023-07-05
  • 怎么用Dreamweaver8对网站文件进行检查整理
    这篇文章主要讲解了“怎么用Dreamweaver8对网站文件进行检查整理”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“怎么用Dreamweaver8对网站文件进行检查整理”吧!  步骤如下:...
    99+
    2023-06-08
  • 怎么用css实现监控网络连接状态的页面
    这篇文章主要介绍怎么用css实现监控网络连接状态的页面,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!   代码解读   navigator.onLine属性用于获取在线状态,再配...
    99+
    2024-04-02
  • Python静态网站生成器Pelican怎么用
    Python静态网站生成器Pelican怎么用,很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。Pelican 是那些想要自我托管简单网站或博客的 Python 用...
    99+
    2023-06-16
  • Android应用怎么实现隐藏状态栏
    这篇文章将为大家详细讲解有关Android应用怎么实现隐藏状态栏,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。  方法一:public class MainActivit...
    99+
    2023-05-31
    android roi
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作