使用Selenium与Python提取鼠标悬停弹出的Airbnb房源入住率数据
解决Inside Airbnb墨尔本地图悬停数据提取问题
你好!我看了你的代码,核心问题出在元素定位不准确——你之前定位的是整个SVG容器,而不是地图上的每个点位(circle元素),同时悬停弹窗的定位也不对。下面是修正后的完整方案:
关键问题修正说明
- 缺少
By模块导入:Selenium定位元素必须用到这个模块,之前的代码会直接报错 - 点位定位错误:应该定位SVG下的每个
<circle>标签,而不是整个SVG容器 - 弹窗定位错误:Inside Airbnb的悬停弹窗使用Leaflet地图组件,标准类名为
leaflet-popup-content,用这个定位更可靠 - 增加了滚动和异常处理:避免元素在视窗外导致悬停失败,同时防止单个点位出错中断整个程序
修正后的完整代码
from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver import ActionChains from selenium import webdriver from selenium.webdriver.common.by import By # 补上这个必要的导入 chrome_options = webdriver.ChromeOptions() # 新版本Chrome建议用webdriver-manager自动管理驱动,避免路径/版本不匹配问题 # from webdriver_manager.chrome import ChromeDriverManager # browser = webdriver.Chrome(options=chrome_options, executable_path=ChromeDriverManager().install()) browser = webdriver.Chrome(options=chrome_options, executable_path='C:\\Users\\Kunal\\chromedriver.exe') browser.get('http://insideairbnb.com/melbourne/') browser.maximize_window() # 等待所有地图点位(circle元素)加载完成 elements = WebDriverWait(browser, 20).until( EC.visibility_of_all_elements_located((By.XPATH, '//*[@id="map"]//svg//circle')) ) data = [] for index, circle in enumerate(elements): try: # 滚动到当前点位中心,确保元素可交互 browser.execute_script("arguments[0].scrollIntoView({block: 'center'});", circle) # 执行鼠标悬停操作 ActionChains(browser).move_to_element(circle).perform() # 等待悬停弹窗加载,定位弹窗内容区域 popup = WebDriverWait(browser, 10).until( EC.visibility_of_element_located((By.CLASS_NAME, 'leaflet-popup-content')) ) # 提取弹窗文本 popup_text = popup.text data.append(popup_text) print(f"已提取第{index+1}个点位数据: {popup_text}") except Exception as e: print(f"提取第{index+1}个点位失败: {str(e)}") continue # 打印第一条数据示例 if data: print("\n第一条数据详情:") print(data[0]) browser.quit()
额外优化:精准提取入住率
如果只需要入住率数据,可以在提取弹窗文本后做字符串解析,比如:
# 从弹窗文本中提取Occupancy(入住率)字段 for popup_text in data: for line in popup_text.split('\n'): if 'Occupancy' in line: occupancy_rate = line.split(':')[-1].strip() print(f"入住率: {occupancy_rate}")
内容的提问来源于stack exchange,提问作者Kunal Dhotre
相关产品推荐
相关产品推荐

