python - 如何单击硒(Python)中的按钮文本
问题描述
希望 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)
解决方案
首先,强烈建议不要使用关键字名称来命名变量。
因此,调用 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()
推荐阅读
- vue.js - Vuetify v-flex offset-*(1-12) 无法正常工作
- haskell - 如何遍历树结构并更改其数据类型
- javascript - ReactJS - net::ERR_FILE_NOT_FOUND
- spring - 在spring Data中使用继承时如何检索对象
- google-cloud-platform - 我应该使用什么服务来处理 Cloud Storage 存储分区中的文件并上传结果?
- java - PostConstruct 不再可用
- c# - 在 C# 中合并两个 .CS 文件以生成新类
- sql-server - ssis 包没有在代理上安排作业执行
- javascript - js获取字母表中的字母个数
- spring - 是否可以从多个微服务(Spring Boot)生成一个war文件?