Python 编解码器可以';t编码字符蟒蛇3
我想从这个网站上获取名称和价格: 名称和价格都在Python 编解码器可以';t编码字符蟒蛇3,python,python-3.x,web-scraping,beautifulsoup,Python,Python 3.x,Web Scraping,Beautifulsoup,我想从这个网站上获取名称和价格: 名称和价格都在div标签中 名称: 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")
div
标签中
名称:
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)
价格
打印名称很好,但打印价格给了我一个错误:
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>
它们之间有什么区别
那么为什么其中一个给我一个错误而另一个没有呢?它产生了这个错误,因为python在货币符号方面遇到了问题。印度卢比符号的解释不同,默认情况下不在python字符映射中。如果我们将上一次打印语句更改为
print(str(price.text.encode(“utf-8”))
,我们将得到如下结果:
b'\xe2\x82\xb961990'
b'\xe2\x82\xb940000'
b'\xe2\x82\xb963854'
b'\xe2\x82\xb934990'
b'\xe2\x82\xb948990'
b'\xe2\x82\xb952990'
b'\xe2\x82\xb932990'
b'\xe2\x82\xb954990'
b'\xe2\x82\xb952990'
因为这个输出不是很漂亮,而且可能不可用,所以我个人会在打印之前截断这个符号。如果确实希望python打印印度卢比符号,可以将其添加到charmap中。按照中的步骤向charmap添加自定义设置。这是否回答了您的问题?Python的哪个版本?使用3.6或更高版本可能会更幸运。Python版本是3.7.4