python - 编解码器无法编码字符python3

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

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

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

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

姓名:

enter image description here

价格

enter image description here

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

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)

enter image description here

它们之间有什么区别?

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

最佳答案

它产生这个错误是因为 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/

相关文章:

python - Openpyxl - 在不同的工作表上创建图表

python - +-r, +-s 的所有排列

python - 插入字节类型的对象

android - 已解决 : Buildozer kivy App crashes on Android right after opening

python - 如何在 tkinter 按钮之间添加特定的像素间距?

python - 将 Web Scraping 的结果存储到数据库中

python - 抓取时查找 <strong> 元素中的类

jquery - Python Flask 获取json数据显示

python - 使用 BeautifulSoup Python 单击按钮后获取值(value)

python - wifijammer.py 问题 MacOSx