问题
I'm using ChromeDriver of Selenium with Python and I'm trying to find a button on my page that has the following HTML:
<input id="j_id0:SiteTemplate:j_id255:new" type="submit" name="j_id0:SiteTemplate:j_id255:new" value="New" class="kbutton-white">
The only thing I know being constant is the id and name ending with "new" and I'm trying to use the following code to identify and click that element:
test_runner.driver.find_element_by_css_selector('[id*=new]').click()
However, I get this error when I run the code:
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":"[id*=new]"}
What's my mistake here?
Update: This element was inside an iframe and I had to switch to the iframe before trying to find the element. Please see comments for the answer.
回答1:
As per the HTML you have shared to invoke click()
on the desired element you can use the following css_selector
:
driver.find_element_by_css_selector("input.kbutton-white[id$='new'][name$='new'][value='New']").click()
Explaination :
.kbutton-white
: The class attribute.id$='new'
: id attribute ends with newname$='new'
: name attribute ends with newvalue='New'
: The value attribute.
But it seems the element is dynamic so you may need to induce WebDriverWait as follows :
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input.kbutton-white[id$='new'][name$='new'][value='New']"))).click()
References
You can find a couple of relevant detailed discussions in:
- Java Selenium webdriver expression finding dynamic element by ccs that starts with and ends with
- How to click a dynamic link with in a drupal 8 website using xpath/css selector while automating through Selenium and Python
- How to get selectors with dynamic part inside using Selenium with Python?
来源:https://stackoverflow.com/questions/50298553/finding-elements-by-css-selector-with-chromedriver-selenium-in-python