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()
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章