N
N
NikClik2018-09-18 02:42:51
Python
NikClik, 2018-09-18 02:42:51

Why does the error "'ascii' codec can't encode characters in position 14-18: ordinal not in range(128)" occur?

The code:

query_string = search_info
    url_string = "https://www.google.co.in/search?q={0}&source=lnms&tbm=isch".format(query_string)
    browses = {
        'User-Agent': "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) "
                      "Chrome/43.0.2357.134 Safari/537.36"
    }
    return BeautifulSoup(
            urllib.request.urlopen(
                urllib.request.Request(url_string, browses)), 'html.parser')

Mistake:
Traceback (most recent call last):
  File "C:/Vk_bot/Start.py", line 64, in <module>
    sender_bot()
  File "C:/Vk_bot/Start.py", line 55, in sender_bot
    img_links = links_list(message.split('!')[1])
  File "C:/Vk_bot/Start.py", line 22, in links_list
    soup = search_in_google(search_info)
  File "C:/Vk_bot/Start.py", line 18, in search_in_google
    urllib.request.urlopen(url_string), 'html.parser'))
  File "C:\Program Files\Python36\lib\urllib\request.py", line 223, in urlopen
    return opener.open(url, data, timeout)
  File "C:\Program Files\Python36\lib\urllib\request.py", line 526, in open
    response = self._open(req, data)
  File "C:\Program Files\Python36\lib\urllib\request.py", line 544, in _open
    '_open', req)
  File "C:\Program Files\Python36\lib\urllib\request.py", line 504, in _call_chain
    result = func(*args)
  File "C:\Program Files\Python36\lib\urllib\request.py", line 1361, in https_open
    context=self._context, check_hostname=self._check_hostname)
  File "C:\Program Files\Python36\lib\urllib\request.py", line 1318, in do_open
    encode_chunked=req.has_header('Transfer-encoding'))
  File "C:\Program Files\Python36\lib\http\client.py", line 1239, in request
    self._send_request(method, url, body, headers, encode_chunked)
  File "C:\Program Files\Python36\lib\http\client.py", line 1250, in _send_request
    self.putrequest(method, url, **skips)
  File "C:\Program Files\Python36\lib\http\client.py", line 1117, in putrequest
    self._output(request.encode('ascii'))
UnicodeEncodeError: 'ascii' codec can't encode characters in position 14-18: ordinal not in range(128)

Question:
What is the problem? I just can't figure out what I messed up?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Eugene, 2018-09-18
@immaculate

import urllib.parse
query_string = urllib.parse.quote(query_string)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question