【问题标题】:How to click on a button text in selenium (Python)如何单击硒(Python)中的按钮文本
【发布时间】:2023-03-05 07:16:01
【问题描述】:

These are the buttons I want selenium to click on

This is what the elements of the 4 buttons showed above look like

想让 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)

【问题讨论】:

    标签: python selenium selenium-webdriver xpath selenium-chromedriver


    【解决方案1】:

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

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

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

    time_el.click()
    

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

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

    【讨论】:

    • 非常感谢您的回答!但是我仍然无法让它工作,在你建议的代码中我想知道 the_time_variable 是什么?我将 the_time_variable 设置为“上午 8:00”,但它没有给我这样的元素错误。
    • 元素是否呈现真实的、不断变化的时间?如果是 - 您不能选择基于完全未知字符串值的元素
    • 不,该元素所在的页面包含许多不同的相同按钮,只是时间部分不同。如果这不起作用,我该如何解决这个问题?
    • 你能分享一个页面链接吗?
    • 我无法发送链接,因为它需要登录才能访问该页面,但是,我在帖子中添加了一些图片。请给他们看看并尝试提供解决方案,我真的很感激:)!
    【解决方案2】:
    from selenium.webdriver.common.by import By
    driver.find_element(By.CSS_SELECTOR,"[data-slottime=text_you_want]").click()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-17
      • 1970-01-01
      • 2023-01-11
      • 2021-12-08
      • 1970-01-01
      • 2023-03-26
      • 2021-08-12
      • 1970-01-01
      相关资源
      最近更新 更多