首页 > 解决方案 > 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 源代码时,我没有找到那个字符。任何想法为什么会出现这个角色?以及如何解决这个问题.. 是使用足够的替换还是有更好的方法?

标签: pythonbeautifulsouppython-requests

解决方案


您可以使用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


推荐阅读