我想从这个网站上抓取名称和价格:
名称和价格都在 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 在处理该货币符号时遇到问题。印度卢比符号有不同的解释depending on the language默认情况下不在 python 字符映射表中。如果我们将最后一个打印语句更改为 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 添加自定义内容。
关于python - 编解码器无法编码字符python3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58719380/