2017-08-11 7 views
0

から不正な要求を私はプログラミングの冒涜エディタ私はHTTPエラー400得続ける:私はUdacityから、私は別のバージョンを使用 原因のPythonを勉強していurlopen

で動けなくなる。これは私のコードです:

import urllib.request 
def readdocument(x): 
    document = open(x) 
    profanitycheck(document.read()) 
    document.close() 
def profanitycheck(urcontent): 
    q = urllib.request.Request("http://www.wdylike.appspot.com/?q="+urcontent) 
    with urllib.request.urlopen(q) as content2: 
     output = content2.read() 
     print(output) 

filelocate=(r"C:\Users\Sutthikiat\Desktop\movie_quotes.txt") 
readdocument(filelocate) 

が、これはTXTファイルです:

-- Houston, we have a problem. (Apollo 13) 

-- Mama always said, life is like a box of chocolates. You never know what you are going to get. (Forrest Gump) 

-- You cant handle the truth. (A Few Good Men) 

-- I believe everything and I believe nothing. (A Shot in the Dark) 

が、私は新しいテキストファイルを作成し、それを確認し、私は自分のコードがエラーを取得する方法を理解していないので、それは多分それはexceptioについてです、正常に動作しますn ??

これはエラーコードです:

Traceback (most recent call last): 
    File "C:\Users\Sutthikiat\Desktop\cursecheck.py", line 13, in <module> 
readdocument(filelocate) 
    File "C:\Users\Sutthikiat\Desktop\cursecheck.py", line 4, in readdocument 
profanitycheck(document.read()) 
    File "C:\Users\Sutthikiat\Desktop\cursecheck.py", line 8, in profanitycheck 
with urllib.request.urlopen(q) as content2: 
    File "C:\Users\Sutthikiat\AppData\Local\Programs\Python\Python36\lib\urllib\request.py", line 223, in urlopen 
return opener.open(url, data, timeout) 
    File "C:\Users\Sutthikiat\AppData\Local\Programs\Python\Python36\lib\urllib\request.py", line 532, in open 
response = meth(req, response) 
    File "C:\Users\Sutthikiat\AppData\Local\Programs\Python\Python36\lib\urllib\request.py", line 642, in http_response 
'http', request, response, code, msg, hdrs) 
    File "C:\Users\Sutthikiat\AppData\Local\Programs\Python\Python36\lib\urllib\request.py", line 570, in error 
return self._call_chain(*args) 
    File "C:\Users\Sutthikiat\AppData\Local\Programs\Python\Python36\lib\urllib\request.py", line 504, in _call_chain 
result = func(*args) 
    File "C:\Users\Sutthikiat\AppData\Local\Programs\Python\Python36\lib\urllib\request.py", line 650, in http_error_default 
raise HTTPError(req.full_url, code, msg, hdrs, fp) 
urllib.error.HTTPError: HTTP Error 400: Bad Request 

答えて

1

サーバーは、無効なそれを考えて、ちょうどこの

urllib.request.urlopen("https://www.baidu.com/s?wd="+"a\nb") 

ようurlinvalid characterが含まれています:\n(コンテンツだけのようなファイルから読み込み)。あなたはそれらをquoteする必要があります:URLを引用についてのあなたの答えのための

from urllib.quote import quote 
q = urllib.request.urlopen("https://www.baidu.com/s?wd="+ urllib.request.quote("a\nb")) 
print(q.url) 
'https://www.baidu.com/s?wd=a%0Ab' 
+0

おかげで(%の意味に気づくことはありません)、今それはurllib.parse.quote() 'または「urllib.request.pathname2urlで正常に動作します: - ) –

関連する問題