【问题标题】:Click on button which changes its id everytime单击每次更改其ID的按钮
【发布时间】:2019-05-05 12:20:33
【问题描述】:

我使用 Python 和 Selenium。 任务是点击带有 text '+like' 的按钮或带有 class 的列 'td' em>='个人资料图片'。 但是按钮没有 id,它的 class 'more-likes' 用于其他按钮。 divclass 'profile-image-button' (在其他 'divs' 中使用 div 的类 ID)的情况相同。 我试图获取 'td' 的 id:

button = photos.find('td', class_='profile-image')
print(button.get_id)

输出为“无”

这是网页的html代码:

<div id="category7515692" class="category-content" data-content="present" data-collapsing="true">
  <table class="pictures" data-columns-count="12" data-type="gallery">
    <tbody class="" data-selec="7565904" data-name="beauty" data-live="true">
      <tr data-mutable-id="MR1main" class="header">
        <td class="main-row-buttons" rowspan="1" data-mutable-id="Bmain">
          <table>
            <tbody>
              <tr>
                <td class="profile-image" id="view-75634" data-event-more-view="event-more-view" data-selec="7565904" islive="true" isseparatedbutton="false">
                  <div class="profile-image-button">
                    <span class="more-likes">+like</span>
                  </div>
                </td>
              </tr>
            </tbody>
          </table>
        </td>
      </tr>
    </tbody>
  </table>
</div>

如何点击按钮或如何获取id?

【问题讨论】:

  • 请提供一个更好的例子,一个不可能的真实例子,以便我们测试它。
  • 我添加了很大一部分 html 代码。希望对我们有帮助

标签: python selenium beautifulsoup webdriverwait mechanicalsoup


【解决方案1】:

假设只有一个带有“+like”文本的按钮,您可以像这样搜索带有特定文本的元素:

driver.find_element_by_xpath("//*[contains(text(), '+like')]").click()

【讨论】:

    【解决方案2】:

    所需的元素是 React 元素,因此要单击该元素,您必须诱导 WebDriverWait 以使 元素可单击,您可以使用以下任一方法解决方案:

    • 使用CSS_SELECTOR

      WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "td.profile-image>div.profile-image-button>span.more-likes"))).click()
      
    • 使用XPATH

      WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//td[@class='profile-image']//span[@class='more-likes' and contains(.,'+like')]"))).click()
      
    • 注意:您必须添加以下导入:

      from selenium.webdriver.support.ui import WebDriverWait
      from selenium.webdriver.common.by import By
      from selenium.webdriver.support import expected_conditions as EC
      

    【讨论】:

    • 感谢您的回答!我听说过有关机械汤的事情。这可能是解决方案吗?抱歉,我从未使用过它...
    • 不知道 mechanicalsoup,您尝试过解决方案吗?请问可以给我状态吗?
    • 天啊!有用!太感谢了!但它只点击一个按钮。我认为我们只用这些参数识别 1 个按钮。但是网页至少有3个按钮。如果我需要点击每个按钮,我应该怎么做? (问题是......当我点击按钮时,它会显示更多我需要解析的信息)
    • 您必须针对您的新要求提出一个新问题,StackOverflow 贡献者将很乐意为您提供帮助。
    • 好的。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2022-01-19
    • 1970-01-01
    • 1970-01-01
    • 2022-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-02
    相关资源
    最近更新 更多