在url中键入中文时发生UnicodeEncodeError


import urllib.request
import bs4
key_word = input('What is the good you are searching for?')
price_low_limit = input('What are the lowest price restrictions?')
price_high_limit = input('What are the highest price restrictions?')
url_jd = 'https://search.jd.com/search?keyword={}&enc=utf-8&qrst=2&rt=1&stop=1&vt=2&wq={}&ev=exprice_{}-{}%5E&uc=0#J_searchWrap'.format(key_word, key_word, price_low_limit, price_high_limit)
response = urllib.request.urlopen(url_jd)
text = response.read().decode()
html = bs4.BeautifulSoup(text, 'html.parser')
total_item_j = []
for information in html.find_all('div', {'class': "gl-i-wrap"}):
for a in information.find_all('a', limit=1):
a_title = a['title']
a_href = a['href']
for prices in information.find_all('i', limit=1):
a = prices.text
item_j = {}
item_j['price'] = float(a)
item_j['name'] = a_title
item_j['url'] = a_href
total_item_j.append(item_j)
print(total_item_j)

这是我在学校做的一个项目。我想使用这个程序来提取我搜索的商品的价格。目前,这段代码可以在python 3.7中用于English Input。然而,例如,如果我用中文搜索商品巧克力'(Chocolate(,结果会是Unicode编码错误。请帮帮我。

您只需要确保您的字符串编码正确。如果将key_word更改为:

key_word = u'巧克力'.encode('utf-8')

你会发现它很好用。

所以你的代码看起来像:

import urllib.request
import bs4
key_word = input('What is the good you are searching for?')
key_word = key_word.encode('utf-8') 
...

关于python中unicode的更多信息,请点击这里

如果您查看堆栈跟踪,您会看到以下内容:

# Non-ASCII characters should have been eliminated earlier
--> 983         self._output(request.encode('ascii'))

key_word变量中的字符的ASCII编码将失败。它们应该首先进行URL转义。使用:

key_word = urllib.parse.quote_plus(key_word)

然后准备url_jd字符串。

相关内容

  • 没有找到相关文章

最新更新