Finding elements by CSS selector with ChromeDriver (Selenium) in Python

纵饮孤独 提交于 2021-02-08 03:01:32

问题


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 new
  • name$='new' : name attribute ends with new
  • value='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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!