Selenium爬取动态加载网页无法获取全部XPath元素求助
问题原因
find_elements_by_xpath返回值为WebElement对象列表,列表本身不具备get_attribute方法,你对列表直接调用该方法会触发异常,异常被try-except捕获后直接执行pass,所以最终得到空列表。而find_element_by_xpath返回单个WebElement对象,调用该方法合法,因此可以拿到第一条链接。- 你当前编写的XPath仅匹配id为
w1的节点,未覆盖w1到w11的所有车辆条目,即使修复第一点问题,也只能拿到每次加载的第一条车辆链接。
修正方案
你可以修改XPath匹配所有id以w开头的车辆节点,再遍历拿到的所有元素逐个提取href属性即可,修正后代码如下:
from selenium import webdriver import time links = [] url = 'https://buy.olxautos.cl/buscar?VehiculoEsSearch%5Btipo_valor%5D=1&VehiculoEsSearch%5Bprecio_range%5D=3990000%3B15190000' # 如果你使用的是Selenium 4.x版本,需要通过Service类指定ChromeDriver路径 driver = webdriver.Chrome() driver.get(url) time.sleep(5) SCROLL_PAUSE_TIME = 3 # 获取滚动高度 last_height = driver.execute_script("return document.body.scrollHeight") while True: # 滚动到页面底部 driver.execute_script("window.scrollTo(0, document.body.scrollHeight);") # 等待页面加载 time.sleep(SCROLL_PAUSE_TIME) # 计算新的滚动高度和旧高度对比 new_height = driver.execute_script("return document.body.scrollHeight") if new_height == last_height: break last_height = new_height try: # 匹配所有id以w开头的节点下的a标签,覆盖w1到w11的所有条目 car_items = driver.find_elements_by_xpath("//*[starts-with(@id,'w')]/div[1]/div/div[1]/a") # 遍历所有元素提取href for item in car_items: links.append(item.get_attribute('href')) except Exception as e: # 调试阶段可以打印异常信息,方便排查问题 print(f"采集出错:{e}") print(links) driver.quit()
版本兼容说明
如果使用的是Selenium 4.x版本,find_elements_by_xpath方法已被弃用,需要替换为如下写法:
from selenium.webdriver.common.by import By car_items = driver.find_elements(By.XPATH, "//*[starts-with(@id,'w')]/div[1]/div/div[1]/a")
内容的提问来源于stack exchange,提问作者Jose_gallego
相关产品推荐
相关产品推荐

