2017-01-06 13 views
0

Google画像から最初のサムネイル画像を保存するための関数を作成しました。しかし、問題は、私が非ansii単語を入力すると失敗するということです:mañanaユニコード文字列のurlopenでurllib.requestが失敗する

エラーメッセージはurllibモジュール内から発生しています。アップ読んだ後、私はいくつかのこの作業、urllibは、urllib2のと要求のためのライブラリ(:urllib3ともピップ経由)がある発見:私は編集のpython 3.6

Traceback (most recent call last): File "c:\users\xxx\Desktop\script.py", line 19, in main() File "c:\users\xxx\Desktop\script.py", line 16, in main save_picture("mañana") File "c:\users\xxx\Desktop\script.py", line 8, in save_picture raw_website = urlopen(request).read() File "C:\Users\xxx\AppData\Local\Programs\Python\Python36\lib\urllib\request.py", line 223, in urlopen return opener.open(url, data, timeout) File "C:\Users\xxx\AppData\Local\Programs\Python\Python36\lib\urllib\request.py", line 526, in open response = self._open(req, data) File "C:\Users\xxx\AppData\Local\Programs\Python\Python36\lib\urllib\request.py", line 544, in _open '_open', req) File "C:\Users\xxx\AppData\Local\Programs\Python\Python36\lib\urllib\request.py", line 504, in _call_chain result = func(*args) File "C:\Users\xxx\AppData\Local\Programs\Python\Python36\lib\urllib\request.py", line 1361, in https_open context=self._context, check_hostname=self._check_hostname) File "C:\Users\xxx\AppData\Local\Programs\Python\Python36\lib\urllib\request.py", line 1318, in do_open encode_chunked=req.has_header('Transfer-encoding')) File "C:\Users\xxx\AppData\Local\Programs\Python\Python36\lib\http\client.py", line 1239, in request self._send_request(method, url, body, headers, encode_chunked) File "C:\Users\xxx\AppData\Local\Programs\Python\Python36\lib\http\client.py", line 1250, in _send_request self.putrequest(method, url, **skips) File "C:\Users\xxx\AppData\Local\Programs\Python\Python36\lib\http\client.py", line 1117, in putrequest self._output(request.encode('ascii')) UnicodeEncodeError: 'ascii' codec can't encode character '\xf1' in position 16: ordinal not in range(128)

を使用しています。減価償却されたライブラリを使用しているため、このエラーが発生していますか?

EDIT2:は、私が期待通りにUnicode文字列を処理要求を、使用して関数を書き直し

+0

コンテキストを持つように完全なトレースバックを投稿してください。 –

答えて

0
import requests 
import mimetypes 
from bs4 import BeautifulSoup 

def save_picture(self, word): 
    search_string = "https://www.google.nl/search?q={}&tbm=isch&tbs=isz:m".format(word) 
    response = requests.get(search_string, headers={'User-Agent': 'Mozilla/5.0'}) 

    #find the tumbnail for first hit 
    soup = BeautifulSoup(response.text, "html.parser") 
    image_location = soup.find("img").get("src") 

    # download image 
    image = requests.get(image_location) 
    content_type = image.headers.get('content-type') 
    ext = mimetypes.guess_extension(content_type) 

    with open(f"{word}{ext}", 'wb') as fd: 
     for chunk in image.iter_content(chunk_size=128): 
      fd.write(chunk) 

完全なトレースバックを追加しました。しかし、ファイルを保存することはもう少し冗長です

関連する問題