首页 > 解决方案 > beautifulsoup 返回的值与 html 中的值不同

问题描述

BeautifulSoup 返回的值与 HTML 代码显示的值不同:

<div class="fieldYear">2013</div>
<div class="fieldMileage">132 000 km</div>

如果我像这样应用beautifulsoup:

from bs4 import BeautifulSoup
import requests

URL_accueil = "https://www.lacentrale.fr/listing?mileageMax=150000&priceMax=17000&priceMin=5000&yearMin=2012&age=1"
page_accueil = requests.get(URL_accueil)
soup = BeautifulSoup(page_accueil.content, "lxml").find('div', {"class": "resultListContainer"})
print(soup)

我会得到 :

2012 146×520 公里

为什么 BeautifulSoup 返回错误的值?我没有2013年和132000公里。

我试图添加

soup = BeautifulSoup(page_accueil.content, "lxml", from_encoding='utf-8') 

但我也从显示的值中得到不同的值。

标签: pythonbeautifulsoup

解决方案


在源代码中,空格可能使用 Unicode char 00A0(不可破坏空格)进行编码。根据您用于阅读源代码的浏览器,您可能会看到一个简单的空格字符(edge、firefox)或等效的 HTML &nbsp;(chrome、opera)。这只是某些浏览器用来帮助您“可视化”空间的特定字符代码的技巧。

编辑:要解决这个问题,只需初始化你的 BeautifulSoup 对象,page_accueil.text而不是page_accueil.content

from bs4 import BeautifulSoup
import requests

URL_accueil = "https://www.lacentrale.fr/listing?mileageMax=150000&priceMax=17000&priceMin=5000&yearMin=2012&age=1"
page_accueil = requests.get(URL_accueil)
soup = BeautifulSoup(page_accueil.text, "lxml")
result = soup.find('div', {"class": "fieldMileage"})

print(result.text)

返回

147 840 km

Edit2:显然,根据用于执行请求的用户代理,返回的页面具有不同的内容......

让我们尝试使用伪造的 Google Chrome 用户代理:

from fake_useragent import UserAgent
# [...]
page_accueil = requests.get(URL_accueil, headers={'User-Agent': str(UserAgent().chrome)})

结果:

134 500 km

推荐阅读