2015-07-28 140 views
1
# -*- coding: UTF-8 -*- 

import urllib.request 
import re 
import os 

os.system("cls") 

url=input("Url Link : ") 

if(url[0:8]=="https://"): 
    url=url[:4]+url[5:] 

if(url[0:7]!="http://"): 
    url="http://"+url 
try : 
    try : 
     value=urllib.request.urlopen(url,timeout=60).read().decode('cp949') 
    except UnicodeDecodeError : 
     value=urllib.request.urlopen(url,timeout=60).read().decode('UTF8') 
    par='<title>(.+?)</title>' 

    result=re.findall(par,value) 
    print(result) 

except ConnectionResetError as e: 
    print(e) 

TimeoutError消失。但是出現ConnectionResetError。這個錯誤是什麼?它是服務器問題嗎?所以它不能解決我?「ConnectionResetError」我該怎麼辦?

+0

這將是很好,如果你可以添加完整回溯 – The6thSense

+0

主頁是[這裏](http://jakjeon.icems.kr/main.do) –

+0

@VigneshKalai什麼是回溯?我能怎麼做? –

回答

1

포기하지마세요!不要放棄!

某些網站需要特定的HTTP標頭,在這種情況下,需要User-agent。所以你需要在你的請求中設置這個頭。

改變你這樣的請求(17 - 20行代碼的)

# Make request object 
request = urllib.request.Request(url, headers={"User-agent": "Python urllib test"}) 

# Open url using request object 
response = urllib.request.urlopen(request, timeout=60) 

# read response 
data = response.read() 

# decode your value 
try: 
    value = data.decode('CP949') 
except UnicodeDecodeError: 
    value = data.decode('UTF-8') 

您可以更改"Python urllib test"到你想要的任何東西。出於統計目的,幾乎每個服務器都使用User-agent

最後,考慮使用appropritate空格,空行,註釋使您的代碼更具可讀性。這對你有好處。


更多閱讀:

+0

謝謝你這個問題已經完成。你是韓國人嗎? –

+0

「python urllib測試」不受影響? –

+0

是的。您可以將其更改爲不爲空的任何字符串。是。我是韓國人:) – mrorno