我一直在开发一个程序,以检查网站是否正常运行.我正在从Excel工作表中获取URL,然后将结果粘贴为True&在同一个Excel工作表中为false,但是对于某些URL,我收到了socket.timeout错误,此后代码无法正常工作.这是代码:
import http.client as httpc
from urllib.parse import urlparse
import pandas as pd
import xlwings as xw
import smtplib
from xlsxwriter import Workbook
import socket
x=[]
df = pd.read_excel (r'xyz.xlsx')
df1=pd.DataFrame(df,columns=['URL'])
print(df1)
url_list=df["URL"].tolist()
print(url_list)
for i in url_list:
def checkUrl(i):
if 'http' not in i:
i= 'https://'+i
p = urlparse(i)
conn = httpc.HTTPConnection(p.netloc,timeout=4)
conn.request('HEAD',p.path)
try:
resp = conn.getresponse()
return resp.status<400
except requests.exceptions.RequestException:
return False
print(checkUrl(i))
x.append(checkUrl(i))
workbook = Workbook('abc.xlsx')
Report_Sheet = workbook.add_worksheet()
Report_Sheet.write(0,1,'Value')
Report_Sheet.write_column(1,x)
workbook.close()
最佳答案
这段代码有很多问题.
原文链接:https://www.f2er.com/python/533171.html>即使URL需要HTTPS,您也可以无条件使用HTTP
>您执行尝试的请求撤出:
> except子句期望有一个request.exceptions.RequestException不能被您的代码抛出
由于您不是在使用请求库,而是在使用较低级别的http.client,因此您只应该期待套接字库中的错误,这些都是OSError的子类.
您的代码可能会变成(请注意:未经测试):
def checkUrl(i):
if 'http' not in i:
i= 'https://'+i
p = urlparse(i)
if (p.scheme == 'http'):
conn = httpc.HTTPConnection(p.netloc,timeout=4)
else:
conn = httpc.HTTPSConnection(p.netloc,timeout=4)
try:
conn.request('HEAD',p.path)
resp = conn.getresponse()
return resp.status<400
except OSError:
return False