首页 > 解决方案 > 如何使用 python selenium 单击带有文本 bb1 的元素

问题描述

<yt-formatted-string id="channel-title" class="style-scope ytd-account-item-renderer">bb1</yt-formatted-string>

低于一个是完整 x 路径的危险查找元素,因为索引可能会更改

self.driver.find_element_by_xpath('/html/body/ytd-app/ytd-popup-container/iron-dropdown/div/ytd-multi-page-menu-renderer/div[4]/ytd-multi-page-menu-renderer/div[3]/div[1]/ytd-account-section-list-renderer[1]/div/ytd-account-item-section-renderer/div/ytd-account-item-renderer[4]/paper-icon-item/paper-item-body/yt-formatted-string[1]').click()

标签: pythonseleniumxpathyoutubecss-selectors

解决方案


要单击文本为bb1的元素,您可以使用以下任一Locator Strategies

  • 使用css_selector

    self.driver.find_element_by_css_selector("yt-formatted-string.style-scope.ytd-account-item-renderer#channel-title").click()
    
  • 使用xpath

    self.driver.find_element_by_xpath("//yt-formatted-string[@class='style-scope ytd-account-item-renderer' and @id='channel-title'][text()='bb1']").click()
    

理想情况下,要单击需要诱导WebDriverWait的元素element_to_be_clickable(),您可以使用以下任一Locator Strategies

  • 使用CSS_SELECTOR

    WebDriverWait(self.driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "yt-formatted-string.style-scope.ytd-account-item-renderer#channel-title"))).click()
    
  • 使用XPATH

    WebDriverWait(self.driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//yt-formatted-string[@class='style-scope ytd-account-item-renderer' and @id='channel-title'][text()='bb1']"))).click()
    
  • 注意:您必须添加以下导入:

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

参考

您可以在以下位置找到一些相关的详细讨论:


推荐阅读