我想寫一個腳本(在這個網頁上)選擇第一個縣,點擊Generate Excel(檔案將下載),選擇第二個縣,點擊Generate Excel所有縣,依此類推。
到目前為止我所擁有的:
import pytest
import time
import json
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
driver = webdriver.Chrome('/usr/bin/chromedriver')
driver.get("https://www2.calrecycle.ca.gov/LGCentral/DisposalReporting/Origin/ExportByCounty")
driver.set_window_size(1920, 1048)
dropdown = driver.find_element(By.ID, "CountyID")
dropdown.find_element(By.XPATH, "//option[. = '[Alameda]']").click()
element = driver.find_element(By.ID, "CountyID")
actions = ActionChains(driver)
actions.move_to_element(element).click_and_hold().perform()
element = driver.find_element(By.ID, "CountyID")
actions = ActionChains(driver)
actions.move_to_element(element).perform()
element = driver.find_element(By.ID, "CountyID")
actions = ActionChains(driver)
actions.move_to_element(element).release().perform()
driver.find_element(By.ID, "SearchButton").click()
問題是我需要更改"//option[. = '[Alameda]']"到每個縣,這將非常耗時。有沒有辦法可以回圈瀏覽縣串列?或者我可以選擇所有可用的縣?
感謝您的時間和幫助。我重視任何反饋/想法/評論。
uj5u.com熱心網友回復:
您可以捕獲元素option內部的標簽select并回圈遍歷它。
這應該適合您(在 Windows 10 上測驗;Chrome 版本 100):
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
import time
driver = webdriver.Chrome(executable_path='D://chromedriver/100/chromedriver.exe')
wait = WebDriverWait(driver, 20)
url = "https://www2.calrecycle.ca.gov/LGCentral/DisposalReporting/Origin/ExportByCounty"
driver.get(url)
select_el = wait.until(EC.presence_of_element_located((By.XPATH, '//select[@id="CountyID"]')))
counties = select_el.find_elements(By.TAG_NAME, 'option')
total_counties = len(counties)
# len - 1 because the 1st option is blank
print(f"Total counties: {total_counties - 1}")
btn = driver.find_element(By.XPATH, '//button[@id="SearchButton"]')
for i in range(1, len(counties)):
print(f"Clicking County - {counties[i].text}")
counties[i].click()
btn.click()
time.sleep(2)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/457818.html
下一篇:SessionNotCreatedError:sessionnotcreated:ThisversionofChromeDriveronlysupportChromeversion97當前瀏覽器版本為
