使用Python+Selenium实现表格分页点击及多县数据遍历求助
问题核心原因
现有代码存在两个逻辑缺陷导致功能无法正常运行:
- 县切换逻辑遗漏了清空输入框的步骤,多次输入会导致县名拼接,无法正确选中目标县,进而表格数据不会按预期更新
- 分页逻辑没有处理点击后的表格加载等待,容易出现点击未生效、数据未更新就继续执行后续逻辑的问题
修正后的核心逻辑
from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.action_chains import ActionChains from selenium.common.exceptions import NoSuchElementException, ElementClickInterceptedException import pandas as pd import time county_df = pd.read_csv('Counties.csv') chrome_driver_path = r'C:\Windows\chromedriver' url = 'https://caearlyvoting.sos.ca.gov/' with webdriver.Chrome(executable_path=chrome_driver_path) as driver: driver.get(url) driver.maximize_window() driver.implicitly_wait(10) actions = ActionChains(driver) county_selector = driver.find_element_by_id('CountyID') for county in county_df['County'][:5]: # 切换县的修正逻辑:先清空原有内容再输入 county_selector.clear() county_selector.send_keys(county) # 等待县对应表格加载完成 time.sleep(1) # 先处理当前县的第一页数据(你的数据抓取逻辑放在这里) # 此处省略你的表格抓取代码 # 修正后的分页逻辑 while True: try: next_page = driver.find_element_by_css_selector(".paginate_button.next") next_btn_classes = next_page.get_attribute("class") if "disabled" in next_btn_classes: break # 处理点击异常,避免偶发的元素遮挡问题 try: actions.move_to_element(next_page).click().perform() except ElementClickInterceptedException: driver.execute_script("arguments[0].click();", next_page) # 等待下一页表格加载完成 time.sleep(0.8) # 下一页数据抓取逻辑放在这里 # 此处省略你的表格抓取代码 except NoSuchElementException: break
补充说明
- 如果要去掉固定的sleep等待,可以替换为显式等待,判断分页按钮的class变化或者表格行的更新,执行效率会更高
- 代码中保留了你原有使用的旧版Selenium元素定位语法,如果你使用的是Selenium 4.0+版本,可以将
find_element_by_*替换为find_element(By.*)的写法即可
内容的提问来源于stack exchange,提问作者pkpto39
相关产品推荐
相关产品推荐

