使用BeautifulSoup点击按钮后无法获取新增div元素求助
解决点击“显示全部”后无法获取展开内容的问题
问题根源
你代码里的核心错误是:用Selenium操作浏览器完成点击“显示全部”后,又通过requests.get(url)重新请求页面。这是一个全新的HTTP请求,和Selenium控制的浏览器会话完全独立,所以拿到的是初始未展开的页面源码,自然获取不到点击后才显示的内容。
修复方案
- 用Selenium当前页面的源码替代requests请求:通过
driver.page_source获取浏览器当前渲染后的页面源码,这才是点击按钮后的最新内容。 - 优化元素定位方式:绝对XPATH(
/html/body/...)非常脆弱,页面结构稍有变化就会失效,改用相对选择器或更稳定的属性定位。 - 增加显式等待:确保元素加载完成后再执行点击、提取操作,避免因页面加载延迟导致的报错。
修改后的完整代码
from bs4 import BeautifulSoup import pandas as pd from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys # 初始化Chrome浏览器,配置放在前面 chrome_options = webdriver.ChromeOptions() chrome_options.add_experimental_option("prefs", {"profile.default_content_settings.cookies": 2}) driver = webdriver.Chrome(options=chrome_options) url = 'https://www.autoscout24.it/ricerca-avanzata?sort=standard&desc=0&ustate=N,U&atype=C&cy=I&mmm=13||&lat=45.5714&lon=12.10799&zip=30037-scorz%C3%A8&zipr=100&source=homepage_search-mask' driver.get(url) # 显式等待同意按钮并点击 wait = WebDriverWait(driver, 10) consent_btn = wait.until(EC.element_to_be_clickable((By.CLASS_NAME, '_consent-accept_1fb0r_111'))) consent_btn.click() # 滚动页面到"显示全部"按钮区域 for _ in range(2): driver.find_element(By.TAG_NAME, 'body').send_keys(Keys.PAGE_DOWN) # 显式等待"显示全部"按钮并点击 show_all_btn = wait.until(EC.element_to_be_clickable((By.XPATH, "//button[contains(text(), 'Mostra tutto')]"))) show_all_btn.click() # 等待展开后的元素加载完成 wait.until(EC.presence_of_all_elements_located((By.CLASS_NAME, 'OptionalEquipmentFilter_optionContainer__HsU8p'))) # 获取当前浏览器的页面源码(关键修改) page_source = driver.page_source soup = BeautifulSoup(page_source, 'html.parser') # 提取配置数据 equipment_list = soup.find_all("div", {"class": "OptionalEquipmentFilter_optionContainer__HsU8p"}) print(f"找到的配置项数量:{len(equipment_list)}") accl = [item.span.text.strip() for item in equipment_list] print(accl) # 关闭浏览器 driver.quit()
关键修改说明
- 移除了
requests.get(url),改用driver.page_source获取操作后的页面源码。 - 所有元素操作都增加了
WebDriverWait显式等待,确保元素可交互后再执行操作,提升稳定性。 - 把Chrome配置移到初始化driver之前,避免重复初始化driver的问题。
- 用包含文本的XPATH定位“显示全部”按钮,比绝对路径更稳定。
内容的提问来源于stack exchange,提问作者Just Gio
相关产品推荐
相关产品推荐

