简体   繁体   English

使用 Python 检查响应时间、长度和 URL 状态(获取代码 200,404 等)

[英]Check Response Time, Length and URL status(get code 200,404 etc ) using Python

I have multiple URL's for that I want to check the status like URL Status(return code like 200,404 etc).我有多个 URL,我想检查像 URL 状态这样的状态(返回代码像 200,404 等)。 Below is the code that will getcode.下面是获取代码的代码。 I want to check response time, length from the same code.我想从相同的代码检查响应时间和长度。 Can anyone help me to modify below code to find response time,length and getcode for multiple urls.任何人都可以帮我修改以下代码以查找多个 url 的响应时间、长度和 getcode。

import socket
from urllib2 import urlopen, URLError, HTTPError

import urllib
socket.setdefaulttimeout( 23 )  # timeout in seconds
#print "---------URL----------", " ---Status Code---"
url='https://www.google.com'

    try :
      response = urlopen( url )
    except HTTPError, e:
        print 'The server couldn\'t fulfill the request. Reason:', str(e.code)
        #Want to get code for that but its not showing

    except URLError, e:
        print 'We failed to reach a server. Reason:', str(e.reasonse)
        #Want to get code for that but its not showing


    else :

        code=urllib.urlopen(url).getcode()
        **#here getcode is working
        print url,"-------->", code
        #print 'got response!' 

I think your use case is better-suited to the Requests library.我认为您的用例更适合 Requests 库。 Install that with pip install requests and check out the documentation .使用pip install requests安装它并查看文档 You should be up and running in no time!您应该立即启动并运行!

Following code will print the response status and headers for all successful requests followed by the time it took to complete it:以下代码将打印所有成功请求的响应状态和标头,以及完成它所花费的时间:

import socket
import time
from urllib2 import urlopen

URLS = ['http://www.google.com', 'http://www.yahoo.com']
socket.setdefaulttimeout( 23 )  # timeout in seconds

for url in URLS:
    print 'Checking URL {0}'.format(url)
    start = time.clock()
    try:
        response = urlopen(url)
        print response.getcode()
        print response.info()
    except StandardError, e:
        print 'Check failed: {0}'.format(e)

    print 'took {0}s\n'.format(time.clock() - start)

Output:输出:

Checking URL http://www.google.com
200
Date: Wed, 23 Mar 2016 05:12:30 GMT
Expires: -1
...

took 0.21013614795s

Checking URL http://www.yahoo.com
200
Date: Wed, 23 Mar 2016 05:12:31 GMT
...

took 0.983750700381s

As @contracode suggested you might want to take a look at requests which is the most popular HTTP library for Python.正如@contracode 所建议的那样,您可能想查看requests ,它是 Python 最流行的 HTTP 库。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM