【问题标题】:codec can't encode character python3编解码器无法编码字符python3
【发布时间】:2019-11-06 23:39:15
【问题描述】:

我想从这个网站上抓取名称和价格:

https://www.flipkart.com/laptops/~buyback-guarantee-on-laptops-/pr?sid=6bo%2Cb5g&uniqBStoreParam1=val1&wid=11.productCard.PMU_V2

名称和价格都在div 标签内。

姓名:

价格

打印名称工作正常,但打印价格给我一个错误:

Traceback (most recent call last):
  File "c:\File.py", line 37, in <module>
    print(price.text)
  File "C:\Python37\lib\encodings\cp1252.py", line 19, in encode
    return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\u20b9' in position 0: character maps to <undefined>

代码:

from selenium import webdriver
from bs4 import BeautifulSoup
import pandas as pd
import requests

response = requests.get("https://www.flipkart.com/laptops/~buyback-guarantee-on-laptops-/pr?sid=6bo%2Cb5g&uniq")
soup = BeautifulSoup(response.text, 'html.parser')
for a in soup.findAll('a',href=True, attrs={'class':'_31qSD5'}):
    name=a.find('div', attrs={'class':'_3wU53n'})
    price=a.find('div', attrs={'class':'_1vC4OE _2rQ-NK'})
    print(name.text)

它们之间有什么区别?

那么为什么其中一个给我一个错误而另一个没有呢?

【问题讨论】:

标签: python python-3.x web-scraping beautifulsoup


【解决方案1】:

它产生了这个错误,因为 python 在那个货币符号上遇到了问题。印度卢比符号的解释不同depending on the language,默认情况下不在pythoncharmap中。如果我们将您最后的打印语句更改为 print(str(price.text.encode("utf-8"))),我们将得到如下所示的结果:

b'\xe2\x82\xb961,990' b'\xe2\x82\xb940,000' b'\xe2\x82\xb963,854' b'\xe2\x82\xb934,990' b'\xe2\x82\xb948,990' b'\xe2\x82\xb952,990' b'\xe2\x82\xb932,990' b'\xe2\x82\xb954,990' b'\xe2\x82\xb952,990'

由于这个输出不是很漂亮并且可能不可用,我会在打印之前亲自截断该符号。如果你真的想要 python 打印印度卢比符号,你可以将它添加到你的charmap中。按照this post 中的这些步骤将自定义添加到charmap。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-17
    • 2013-08-01
    • 2015-11-21
    • 2016-02-12
    • 1970-01-01
    • 2016-10-04
    • 2015-06-27
    • 2015-10-21
    相关资源
    最近更新 更多