Python3 检测网址(url)有效性,并将报告结果保存到CSV

Python3 检测网址(url)有效性,并将报告结果保存到CSV


# @author: huangyanli
# @date : 2018-05-11 23:45:00
# @QQ : 339600718
# @Email : [email protected]
# 检测网址的有效性,并打印报告结果。


from urllib import error, request

# 要检测得网址list
urls = ["http://www.cache-cache.cn/store-finder/1", "http://1314.qq.com/", "https://www.2345.com/", "https://www.csdn.net/", "https://www.csdn3.net/"]

f = open(r"url_check.csv", "w", encoding="utf-8")
# 写入title
f.write('url, reason,code\n')
# 遍历每一个url
for url in urls:
    try:
        response = request.urlopen(url)
        # 如果是有效连接,则写入url,code
        f.write(url + ",," + str(response.getcode()) + "\n")
    except error.URLError as e:
        try:
            # 如果网站返回错误,则写入url,code,错误原因
            f.write(url + "," + e.reason + "," + str(e.getcode()) + "\n")
        except:
            # 如果服务器不存在则写入url,错误原因
            f.write(url + "," + str(e.reason) + "\n")
f.close()

你可能感兴趣的:(Python)