You need to enable JavaScript to run this app. Python网页爬虫用Selenium提交表单后为何仅提取到首页数据
优惠活动
大模型
产品
解决方案
定价
更多

Python网页爬虫用Selenium提交表单后为何仅提取到首页数据

问题成因
  • 缺少页面加载等待逻辑:点击搜索按钮后,未等待结果页跳转、数据异步渲染完成就立即获取当前URL发起请求,此时拿到的内容仍为首页数据。
  • requests请求无有效会话:该站点的搜索结果依赖表单提交后生成的临时会话凭证、Cookie,直接用requests发起独立请求不会携带Selenium浏览器实例中的会话信息,无法拿到权限校验后的搜索结果。
  • 工具混用逻辑冗余:已使用Selenium完成页面交互、渲染,无需额外调用requests重复请求页面,直接读取Selenium加载完成的页面源码即可。
可运行的修正代码
from selenium import webdriver
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from bs4 import BeautifulSoup
import pandas as pd

# Windows路径可加r避免转义问题
PATH = r"C:\chromedriver.exe"
driver = webdriver.Chrome(PATH)
driver.get('https://tn.tunisiebooking.com/')
wait = WebDriverWait(driver, 20)

# 执行JS填充表单
script = "document.getElementById('ville_des').value ='Sousse';document.getElementById('depart').value ='05/08/2021';document.getElementById('checkin').value ='05/08/2021';document.getElementById('select_ch').value = '1';"
driver.execute_script(script)

# 点击搜索按钮
driver.find_element(By.ID, 'boutonr').click()

# 等待结果页的酒店标题元素加载完成
wait.until(EC.presence_of_element_located((By.CLASS_NAME, 'bloc_titre')))

# 直接读取Selenium渲染好的页面源码
soup = BeautifulSoup(driver.page_source, 'html.parser')
results = soup.find_all('div', attrs={'class':'bloc_titre'})

records = []
for result in results:
    nom = result.find('a').text
    records.append(nom)

df = pd.DataFrame(records, columns=['nom'])
print(df.head())

# 操作完成后关闭浏览器释放资源
driver.quit()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 08:51:02