【问题标题】:How to search for specific text within HTML cell event and click corresponding button within same cell?如何在 HTML 单元格事件中搜索特定文本并单击同一单元格中的相应按钮?
【发布时间】:2021-07-16 05:02:19
【问题描述】:

我的第一个 python 项目需要一些帮助(也是我在 stackoverflow 上的第一篇文章)。感谢您的时间和帮助!

我正在尝试使用 selenium 和 chrome webdriver 在网站上自动进行定期预订。预订页面是一个时间表,每个单元格对应一个时间段,每个单元格/时间段内都有“预订”按钮。

但是,这些按钮的 XPATH 是动态的。

例如//*[@id="root"]/div[4]/div/div[4]/div/div[3]/div[69]/div[3]/button

不同时间段的每个单元格和按钮都具有相同的 html 类名称和类型。那么是否可以在每个单元格中搜索文本(例如 Class 1.10 7:30)并单击同一单元格中的相应按钮?

<div class="column">
  <div class="cell  even">
    <span class="d-block d-sm-none">Sat, 17th Jul</span>
    <span class="d-none d-sm-block">Saturday, 17th July</span></div>

  <div class="cell event " style="color: rgb(255, 255, 255); top: 8rem; height: 6rem;">
    <div>Class 1.1</div>
    <div>07:30</div>
    <div class="position-relative">
      <button class="btn btn-warning" type="button">Book</button>
    </div>
  </div>
    
  <div class="cell event " style="color: rgb(255, 255, 255); top: 16rem; height: 6rem;">
    <div>Class 1.2</div>
    <div>08:30</div>
    <div class="position-relative">
      <button class="btn btn-warning" type="button">Book</button>
      </div>
    </div>

【问题讨论】:

    标签: python xpath selenium-chromedriver


    【解决方案1】:

    是的,这是可能的。
    如果您想匹配 2 个元素中的 2 个文本,如您提供的 HTML 中所示,我猜这些文本作为参数传递给方法,它将是这样的:

    btn_xpath = ("//div[./div[contains(text(),'Class $class')] and (./div[contains(text(),'$time')])]//button[text()='Book']",(class=class, time=time))
    driver.find_element_by_xpath(btn_xpath).click()
    

    这里的classtime 是从外部传递的参数,用于选择所需的班级和时间。
    如果选择可以是唯一的,那么它会是这样的:

    btn_xpath = ("//div[./div[contains(text(),'$time')]]//button[text()='Book']",(time=time))
    driver.find_element_by_xpath(btn_xpath).click()
    

    【讨论】:

    • 非常感谢,这是完美的。你知道关于这个主题的任何资源让我阅读更多吗?它有效,但我不太了解语法/如何。
    • 您应该了解 XPath。尤其是 Selenium 的 XPath,因为存在许多更复杂的 XPath 东西,但 Selenium 不支持,因为 Selenium 仅支持 XPath 1.0 版本而存在 XPath 2.0 等。我不能指出任何具体的教程,只是不要'不记得我是从哪里学到这一切的。所以只要谷歌一下 XPath 定位器和 Selenium 的 XPath 定位器。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多