You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python网页爬取问题:HTML代码提取不完整

爬虫HTML提取不完整及语言切换问题解决

问题分析

你遇到两个核心问题:

  • 目标页面的德语文本被替换为英文
  • 评分相关的<div class="index__scoreBlock__KZCPC">及内部span元素未被提取到

以下是针对性的解决方案:

1. 修正浏览器语言,获取德语内容

网站会根据浏览器语言偏好返回对应语言的内容,ChromeDriver默认语言可能为英文,需手动设置为德语:

from selenium.webdriver.chrome.options import Options

chrome_options = Options()
chrome_options.add_argument("--lang=de")  # 指定浏览器语言为德语
driver = webdriver.Chrome(options=chrome_options)
driver.get("https://www.kununu.com/de/adidas/kommentare")

2. 等待元素完全渲染后再提取HTML

你调用了make_mini_scores_visible(driver)但未等待元素加载完成就提取HTML,需添加显式等待确保评分区块渲染完毕:

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time

# 执行你的点击操作
show_more_reviews(driver, 5)
make_mini_scores_visible(driver)

# 等待评分区块全部加载完成,最长等待10秒
WebDriverWait(driver, 10).until(
    EC.presence_of_all_elements_located((By.CLASS_NAME, "index__scoreBlock__KZCPC"))
)

# 可选:滚动到所有评分区块位置,确保元素被渲染
score_blocks = driver.find_elements(By.CLASS_NAME, "index__scoreBlock__KZCPC")
for block in score_blocks:
    driver.execute_script("arguments[0].scrollIntoView({behavior: 'smooth', block: 'center'});", block)
    time.sleep(0.3)  # 给页面一点渲染时间

# 提取完整HTML
all_reviews = driver.execute_script("return document.documentElement.innerHTML;")
soup = BeautifulSoup(all_reviews, 'html.parser')  # 注意:原代码中变量名错误,需用all_reviews替代html

3. 代码错误修正

原代码中soup = BeautifulSoup(html, 'html.parser')的html变量未定义,需替换为你实际提取的all_reviews变量,否则会抛出NameError。

内容的提问来源于stack exchange,提问作者user23501892

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 23:47:47