python - html源python BeautifulSoup中不存在奇怪的字符
问题描述
我看过一个视频,教如何使用 BeautifulSoup 并请求抓取网站 这是代码
from bs4 import BeautifulSoup as bs4
import requests
import pandas as pd
pages_to_scrape = 1
for i in range(1,pages_to_scrape+1):
url = ('http://books.toscrape.com/catalogue/page-{}.html').format(i)
pages.append(url)
for item in pages:
page = requests.get(item)
soup = bs4(page.text, 'html.parser')
#print(soup.prettify())
for j in soup.findAll('p', class_='price_color'):
price=j.getText()
print(price)
我运行良好的代码。但至于结果,我注意到欧元符号之前有奇怪的字符,并且在检查 html 源代码时,我没有找到那个字符。任何想法为什么会出现这个角色?以及如何解决这个问题.. 是使用足够的替换还是有更好的方法?
解决方案
您可以使用page.content.decode('utf-8')
而不是page.text
. 正如评论中的人所说,这是一个编码问题,.content
并将 HTML 作为字节返回,然后您可以使用 将其转换为具有正确编码的字符串.decode('utf-8')
,而.text
返回具有错误编码的字符串(可能是 cp1252)。最终代码可能如下所示:
from bs4 import BeautifulSoup as bs4
import requests
import pandas as pd
pages_to_scrape = 1
pages = [] # You forgot this line
for i in range(1,pages_to_scrape+1):
url = ('http://books.toscrape.com/catalogue/page-{}.html').format(i)
pages.append(url)
for item in pages:
page = requests.get(item)
soup = bs4(page.content.decode('utf-8'), 'html.parser') # Replace .text with .content.decode('utf-8')
#print(soup.prettify())
for j in soup.findAll('p', class_='price_color'):
price=j.getText()
print(price)
这应该有希望工作
PS:抱歉直接写答案,我没有足够的声誉在评论中写:D
推荐阅读
- sql - 如何通过 sql server express 连接 AWS sql server
- sql - AWS Athena (Presto) 偏移支持
- android - 当您更改并返回成绩选项卡时如何刷新选项卡式活动?
- ios - 无法分配给属性:“宽度”是仅获取属性
- javascript - 解析:ParseError { 代码:101,消息:'找不到对象。' }
- cassandra - 是否有一种惯用的方式将客户端版本控制到数据库?
- c# - 如何在 saveChanges() 中获取错误的实体
- javascript - 当有一个内部循环时,地图没有返回数组
- macos - Mac 安装程序覆盖文件的所有副本
- python - 如何将 DjangoRestFramework permissin_classes 关系设置为“或”?