我正在将 Selenium 的 ChromeDriver 与 Python 一起使用,并试图在我的页面上找到一个具有以下 HTML 的按钮:
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">
我知道唯一不变的是 id 和 name 以new"结尾,我正在尝试使用以下代码来识别并单击该元素:
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]"}
我的错误是什么?
更新:此元素位于 iframe 中,我必须先切换到 iframe,然后才能尝试找到该元素.答案请看评论.
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.
根据您共享的 HTML,在所需元素上调用 click() 您可以使用以下 css_selector代码>:
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()
说明:
.kbutton-white : class 属性.id$='new' : id 属性以 newname$='new' : name 属性以 newvalue='New' :value 属性..kbutton-white : The class attribute.id$='new' : id attribute ends with newname$='new' : name attribute ends with newvalue='New' : The value attribute.但似乎元素是动态的,因此您可能需要如下诱导 WebDriverWait :
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()
您可以在以下位置找到一些相关的详细讨论:
You can find a couple of relevant detailed discussions in:
这篇关于在 Python 中使用 ChromeDriver (Selenium) 通过 CSS 选择器查找元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
如何在python中的感兴趣区域周围绘制一个矩形How to draw a rectangle around a region of interest in python(如何在python中的感兴趣区域周围绘制一个矩形)
如何使用 OpenCV 检测和跟踪人员?How can I detect and track people using OpenCV?(如何使用 OpenCV 检测和跟踪人员?)
如何在图像的多个矩形边界框中应用阈值?How to apply threshold within multiple rectangular bounding boxes in an image?(如何在图像的多个矩形边界框中应用阈值?)
如何下载 Coco Dataset 的特定部分?How can I download a specific part of Coco Dataset?(如何下载 Coco Dataset 的特定部分?)
根据文本方向检测图像方向角度Detect image orientation angle based on text direction(根据文本方向检测图像方向角度)
使用 Opencv 检测图像中矩形的中心和角度Detect centre and angle of rectangles in an image using Opencv(使用 Opencv 检测图像中矩形的中心和角度)