2016-12-02 1 views
0

存在doesnot URLがある場合、スクリプトが壊れると、HTTPレスポンスを取得するためのコードです:http応答を取得するスクリプトを作成しました。但し、下記の

import requests 
import xlrd 
import xlwt 

file_location = "C:/Users/Nitin Kansal/Desktop/rc/Cashkaro.xlsx" 
workbook = xlrd.open_workbook(file_location) 
sheet = workbook.sheet_by_index(0) 

urls = [] 
for r in range(sheet.nrows): 
    urls.append(sheet.cell_value(r,0)) 

book = xlwt.Workbook(encoding = "utf-8", style_compression = 0) 
sheet = book.add_sheet("Sheet1", cell_overwrite_ok = True) 

for index, url in enumerate(urls): 
    r_response = requests.head(url) 

    try: 
     Response_Number = r_response.status_code 
     sheet.write(index, 0, url) 
     sheet.write(index, 1, Response_Number) 

    except Exception: 
     sheet.write(index, 0, url) 
     sheet.write(index, 1, "Failed to Fetch Response") 

book.save("Response Output.xls") 

以下は、Excelにそれらを保存し、URLです、私は、URL「nitinkansal121を追加しました。 com "は存在しません。これはコードを破壊します。このURLが削除された場合、コードはうまく動作します。

https://clk.omgt5.com/?AID=183476&PID=9319&WID=33968 
http://clk.omgt5.com/?AID=183476&PID=9166&WID=33968 
http://clk.omgt5.com/?AID=183476&PID=14173&WID=33968 
http://www.nitinkansal121.com/ 
http://clk.omgt5.com/?AID=183476&PID=9394&WID=33968 
+0

は、実際の要求にtry/exceptブロックを追加してみ? –

+1

エラーが発生した行は何行ですか?エラーは何ですか?私の推測では、r_responseのNoneTypeを取得します。その場合は、r_responseでチェックしてください: – molig

答えて

2

requests.headは、存在しないドメインのURLを渡すと例外が発生します。

r_response = requsts.head(url) 

をのようなもので:あなたは置き換えることができ

try: 
    r_response = requests.head(url) 
except requests.exceptions.ConnectionError: 
    sheet.write(index, 0 , url) 
    sheet.write(index, 1, "Connection error") 
関連する問題