[英]Clicking a button by class name using selenium with python
可能是一个愚蠢的问题,但我花了很多时间来弄清楚这个问题。 我正在 python 中使用 selenium 构建一个 scrapper bot,我只是想点击 web 页面上的一个按钮。 web 页面打开并调整大小...
def initalize_browser():
driver.get("**website name**")
driver.maximize_window()
但我无法让它点击特定按钮。 这是按钮 HTML 代码:
<button class="mx-auto green-btn btnHref" onclick="window.location ='/medical'" onkeypress="window.location='/medical'">
Medical and Hospital Costs
</button>
这是我的代码:
click_button=driver.find_element(by=By.CLASS_NAME, value="mx-auto green-btn btnHref")
click_button.click()
这是我为这段代码得到的错误:
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":".mx-auto green-btn btnHref"}
我已经尝试了很多这样的变体,包括:
driver.find_element_by_xpath('//button[@class="mx-auto green-btn btnHref"]').click()
我在哪里收到此错误:
AttributeError: 'WebDriver' object has no attribute 'find_element_by_xpath'
我还检查了是否有任何其他属性具有相同的 class 名称,但没有。 任何帮助将不胜感激,谢谢!
现在不推荐使用find_element_by_xpath
方法。 使用这一行:
driver.find_element(By.XPATH, '//button[@class="mx-auto green-btn btnHref"]').click()
代替:
driver.find_element_by_xpath('//button[@class="mx-auto green-btn btnHref"]').click()
并确保你在进口中有这个:
from selenium.webdriver.common.by import By
定位器click_button=driver.find_element(by=By.CLASS_NAME, value="mx-auto green-btn btnHref")
不起作用,因为By.CLASS_NAME
只需要一个 class 名称来查找元素,但您给了它 3 class名字。 html 属性class
由按空格分隔的元素列表组成。 所以,在这个 html 代码中
<button class="mx-auto green-btn btnHref" onclick="window.location ='/medical'" onkeypress="window.location='/medical'">
Medical and Hospital Costs
</button>
属性class
有 3 个 class 名称mx-auto
, green-btn
和btnHref
您不能将所有 3 个类与By.CLASS_NAME
一起使用,但您可以使用By.XPATH
使用所有这些类
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.