python脚本--测试网页是否正常运行

使用requests去请求

导库

import requests

添加网址
url = "http://www.baidu.com/"
发出请求,并设置超时时间为5秒
r = requests.get(url, timeout=5)
获取状态码
code = r.status_code
判断
if code == 200:
   print("OK 网站访问正常")
else:
   print("Error 不能访问")

使用urlopen

from urllib.request import urlopen

url = 'http://www.baidu.com'
resp = urlopen(url)
code = resp.getcode()
print('the result is :', code)

使用urllib.request

导入
import urllib.request
建立一个请求,并添加请求头
opener = urllib.request.build_opener()
opener.addheaders = [('User-agent', 'Mozilla/49.0.2')]
读取一个文件到一个列表
file = open('url.txt')
lines = file.readlines()
aa = []
for line in lines:
    temp = line.replace('\n', '')
    aa.append(temp)
print(aa)
遍历列表并发出请求
for a in aa:
    tempUrl = a
    try:
        opener.open(tempUrl)
        print(tempUrl + '正常访问')
    except urllib.error.HTTPError:
        print(tempUrl + '=访问页面出错,HTTPError')
    except urllib.error.URLError:
        print(tempUrl + '=访问页面出错,URLError')
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值