Selenium爬取Tunisiebooking酒店点击食宿方案后显示的动态价格问题求助
问题解决方法
核心思路
该站点的食宿方案价格属于点击触发的动态加载内容,你需要按以下逻辑调整代码即可拿到对应数据:
- 遍历每个酒店下的所有食宿方案可点击元素,逐个触发点击操作
- 每次点击后等待对应价格节点加载完成,再提取当前食宿方案对应的价格
- 收集完单个酒店的所有「食宿方案-价格」对后,再处理下一个酒店
注意事项
- 优先使用Selenium显式等待替代固定sleep,既提升爬取效率也能避免网络波动导致的提取失败
- 部分元素可能被页面悬浮内容遮挡,使用JavaScript执行点击操作可以避免常规点击报错
- 提取价格前可以增加非空判断,避免拿到无效的空值
修改后完整代码
#!/usr/bin/env python # coding: utf-8 import json from time import sleep from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait, Select from selenium.common.exceptions import TimeoutException # create path and start webdriver PATH = "C:\chromedriver.exe" driver = webdriver.Chrome(PATH) # 隐式等待设置 driver.implicitly_wait(5) # first get website driver.get('https://tn.tunisiebooking.com/') wait = WebDriverWait(driver, 20) # params to select params = { 'destination': 'El Jem', 'date_from': '08/08/2021', 'date_to': '09/08/2021', 'bedroom': '1' } # select destination destination_select = Select(driver.find_element_by_id('ville_des')) destination_select.select_by_value(params['destination']) # select bedroom bedroom_select = Select(driver.find_element_by_id('select_ch')) bedroom_select.select_by_value(params['bedroom']) # select dates script = f"document.getElementById('depart').value ='{params['date_from']}';" script += f"document.getElementById('checkin').value ='{params['date_to']}';" driver.execute_script(script) # click bouton search btn_rechercher = driver.find_element_by_id('boutonr') btn_rechercher.click() sleep(10) # ---------------------------------------------------------------------------- # 存储最终结果的字典,符合你要求的输出格式 result_dict = {} hotels_objects = driver.find_elements_by_xpath( '//div[contains(@class, "enveloppe_produit")]' ) for hotel_obj in hotels_objects: # 获取酒店名称 hotel_name = hotel_obj.find_element_by_xpath('.//span[contains(@class, "tittre_hotel")]//a//h3').text.strip() if not hotel_name: continue # 初始化当前酒店的方案价格列表 arrangement_price_list = [] # 获取所有食宿方案的可点击元素 arrangement_btns = hotel_obj.find_elements_by_xpath('.//div[contains(@class, "angle")]') for btn in arrangement_btns: try: # 提取方案名 arrangement_name = btn.find_element_by_xpath('.//u').text.strip() # 用js点击方案按钮,避免被遮挡报错 driver.execute_script("arguments[0].click();", btn) # 等待价格加载完成 wait.until(lambda x: hotel_obj.find_element_by_xpath('.//div[contains(@id, "prixtotal")]').text.strip() != '') # 提取当前价格 price = hotel_obj.find_element_by_xpath('.//div[contains(@id, "prixtotal")]').text.strip() # 添加到列表 arrangement_price_list.append((arrangement_name, price)) except TimeoutException: # 单个方案加载失败直接跳过,不影响其他数据提取 continue # 存入最终结果 result_dict[hotel_name] = arrangement_price_list # 输出结果,就是你要的格式 print(json.dumps(result_dict, ensure_ascii=False, indent=2)) # 关闭浏览器 driver.quit()
运行上述代码后就会直接输出你要求格式的酒店食宿方案和对应价格数据。
内容的提问来源于stack exchange,提问作者HiFAR
相关产品推荐
相关产品推荐

