繁体   English   中英

为什么我找不到带有 selenium 的元素?

[英]Why can't I find element with selenium?

所以我尝试了几乎所有我知道的方法,包括 xpath 什么都没有。 它应该是一个简单的查找元素并单击,仅此而已,但我无法弄清楚。

在此处输入图像描述

这是我的代码

from selenium import webdriver
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary
from selenium.webdriver.firefox.firefox_profile import FirefoxProfile

ff_options = Options()

#profile
binary = FirefoxBinary("C:\\Program Files\\Mozilla Firefox\\firefox.exe")
profile = webdriver.FirefoxProfile('C:\\Users\\bravoj\\AppData\\Roaming\\Mozilla\\Firefox\\Profiles\\7k4o5psw.CCC Deafualt')
ff_driver = webdriver.Firefox(executable_path='C:\\Users\\bravoj\Downloads\\geckodriver.exe')
#fire fox driver
ff_driver.get('about:profiles')
#ff_driver.get('about:preferences#home')

ff_driver.find_element_by_id('profiles-set-as-default').click()

也有重复的代码在此处输入图像描述

'profiles-set-as-default'不是id属性,它是data-l10n-id属性。 您可以使用css_selector来定位它,并使用带有data-l10n-args {CCC Deafult}先前兄弟元素获取唯一元素

ff_driver.find_element_by_css_selector('[data-l10n-args*="CCC Deafult"] ~ [data-l10n-id="profiles-set-as-default"]')

将文本设置为默认配置文件的元素是动态元素,因此要在元素上定位和click() ,您必须为element_to_be_clickable()诱导WebDriverWait ,您可以使用以下任一定位器策略

  • 使用CSS_SELECTOR

     WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "div.tab#profiles button[data-l10n-id='profiles-set-as-default']"))).click()
  • 使用XPATH

     WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[@data-l10n-id='profiles-set-as-default' and text()='Set as default profile']"))).click()
  • 注意:您必须添加以下导入:

     from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM