python - Selenium 驱动程序: How to find the element added after the webpage is loaded?

标签 python python-3.x selenium selenium-chromedriver

所以网页有一个按钮,单击后会向网页添加一个元素,但我在其中找不到使用 selenium

以下一些想象的代码来解释我遇到的问题:

from selenium import webdriver
d = webdriver.Chrome()
#Go to my target website
d.get("https://some_website_url") #ref1
#Okay now loading of the website is done. `d` will not be updated and this is the problem!!

#Click my target button and an element with id="SecretButton" is loaded.
d.find_element_by_css_selector("#secretlyupdatethewebpage").click()

#Find #SecretButton but to no avail. 
#It can be found in the html panel of Chrome Developer Tools
#but cannot be found in the webdriver `d`, as `d` won't be 
#updated after #ref1
d.find_element_by_css_selector("#SecretButton").click()

如何找到#SecretButton?

最佳答案

要查找并调用 secret 按钮上的 click(),您需要为 element_to_be_clickable() 引发 WebDriverWait,您可以使用以下 Locator Strategies :

  • 使用ID:

    WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.ID, "SecretButton"))).click()
    
  • 使用CSS_SELECTOR:

    WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "#SecretButton"))).click()
    
  • 使用XPATH:

    WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//*[@id='SecretButton']"))).click()
    
  • 注意:您必须添加以下导入:

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

关于python - Selenium 驱动程序: How to find the element added after the webpage is loaded?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60463124/

相关文章:

python - 如何在 Python 中集成 HTML

python - 如何在 pip 中安装具有公共(public)依赖项的私有(private)模块?

python - 去如何实现python binascii.unhexlify方法?

python - workpool 与 windows 上的 python3.4 兼容吗?

javascript - Selenium:使用 C# 在 IWebElement 上触发鼠标滚轮

c# - Selenium PageObjects 的定位器对象不能为 null

python - 有没有办法在函数外部从已部署的 Google Cloud Function 导入 python 帮助程序库?

python - Spark 读取 python3 pickle 作为输入

python - 每当单元测试失败时执行操作

selenium - 使用 Proguard 混淆基于 Appium 的 jar 时重复类定义