首页 > 解决方案 > 如何单击硒(Python)中的按钮文本

问题描述

这些是我希望 selenium 点击的按钮

这就是上面显示的 4 个按钮的元素的样子

希望 selenium 使用以下元素单击此按钮:

<div id="book_e43c607b-0fba-472e-ab84-7dd8ff6efb6b" class="time-slot"
 data-slotclub="calgary" data-slotdate="Saturday, 17 July 2021"
 data-slottime="at 5:00 PM">
<div class="time-slot-clock"></div>
<div class="time-slot-box">
    <div class="time-slot-data-line">Saturday, 17 July 2021</div>
    <div class="time-slot-data-line">at 5:00 PM</div>
    <div class="time-slot-data-line">Click to reserve</div>
</div>

然而,与其使用 XPath 或类来查找按钮,我想看看是否有办法使用上面块中第三行的“data-slottime="at 5:00 PM"”部分。我尝试使用下面的代码单击按钮,但是找不到元素。

time = driver.find_element_by_link_text("at 8:00 AM")
driver.execute_script("arguments[0].click();", time)

但是,此代码有效,但使用了我不感兴趣的唯一 x 路径:

time = driver.find_element_by_xpath("//*[@id=\"book_1178d802-ba18-4742-9dce-aac877ad3efb\"]/div[2]/div[1]")  

driver.execute_script("arguments[0].click();", time)

标签: pythonseleniumselenium-webdriverxpathselenium-chromedriver

解决方案


首先,强烈建议不要使用关键字名称来命名变量。
因此,调用 web elementtime是一种不好的做法。
现在,如果你想通过文本选择 web 元素,可以这样做:

time_el = driver.find_element_by_xpath("//div[contains(text(),'the_time')]")

.click()此外,除非您别无选择,否则不建议使用 JavaScript 而不是 selenium 方法单击元素。
所以我宁愿使用这个:

time_el.click()

我猜你会在这里将时间作为参数传递,在这种情况下它可能是这样的:

time_el = driver.find_element_by_xpath("//div[contains(text(),'{0}')]").format(the_time_variable)
time_el.click()

推荐阅读