【问题标题】:Why can't I find element with selenium?为什么我找不到硒元素?
【发布时间】:2019-11-20 06:16:17
【问题描述】:

所以我几乎尝试了所有我知道的方法,包括 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()

也有重复的代码

【问题讨论】:

    标签: python selenium selenium-firefoxdriver


    【解决方案1】:

    '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"]')
    

    【讨论】:

    • 这确实有效。但它一直选择第二个配置文件而不是我瞄准的第三个配置文件,原因是第一个配置文件也具有与元素相同的代码集。所以代码将运行并找到第一个。有没有办法让它跳过它并找到第二个。我提供了一张图片
    【解决方案2】:

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

    • 使用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
      

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-08-17
      • 2020-08-17
      • 1970-01-01
      相关资源
      最近更新 更多