无法使用Selenium Firefox单击元素

zbdgwd5y  于 2022-12-13  发布在  其他
关注(0)|答案(1)|浏览(179)

我正在尝试打开此网页
https://albo-on-line.comune.verona.it/web/servizi/albo-pretorio
使用以下代码:

  1. # selenium 4
  2. from selenium import webdriver
  3. from selenium.webdriver.firefox.service import Service as FirefoxService
  4. from selenium.webdriver.firefox.webdriver import WebDriver
  5. from webdriver_manager.firefox import GeckoDriverManager
  6. driver: WebDriver = webdriver.Firefox(service=FirefoxService(GeckoDriverManager().install()))
  7. url = "https://albo-on-line.comune.verona.it/web/servizi/albo-pretorio"
  8. driver.get(url)
  9. driver.implicitly_wait(10)
  10. cookies = driver.find_element(By.xpath('//*[@id="cookie-privacy-close"]')).click()
  11. determinazioni = driver.findElement(By.xpath('//*[@id="_menucontroller_WAR_maggiolialbopretorioportlet_MenuItem9"]')).click()

但没有成功
你能帮我吗?
thx的

qnakjoqk

qnakjoqk1#

这里有几点需要改进:
1.语法错误。
应该是driver.find_element(By.XPATH, '//*[@id="cookie-privacy-close"]')而不是driver.find_element(By.xpath('//*[@id="cookie-privacy-close"]'))
1.应使用WebDriverWaitexpected_conditions显式等待,而不是implicitly_wait
1.因为您是通过ID来定位这些元素的,所以最好是通过ID来定位这些元素,而不是通过XPath。
下面的代码是有效的:

  1. from selenium import webdriver
  2. from selenium.webdriver.chrome.service import Service
  3. from selenium.webdriver.chrome.options import Options
  4. from selenium.webdriver.support.ui import WebDriverWait
  5. from selenium.webdriver.common.by import By
  6. from selenium.webdriver.support import expected_conditions as EC
  7. options = Options()
  8. options.add_argument("start-maximized")
  9. webdriver_service = Service('C:\webdrivers\chromedriver.exe')
  10. driver = webdriver.Chrome(options=options, service=webdriver_service)
  11. wait = WebDriverWait(driver, 30)
  12. url = "https://albo-on-line.comune.verona.it/web/servizi/albo-pretorio"
  13. driver.get(url)
  14. wait.until(EC.element_to_be_clickable((By.ID, 'cookie-privacy-close'))).click()
  15. wait.until(EC.element_to_be_clickable((By.ID, '_menucontroller_WAR_maggiolialbopretorioportlet_MenuItem9'))).click()

其结果是:

展开查看全部

相关问题