所以网页有一个按钮,单击后会向网页添加一个元素,但我在其中找不到使用 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/