【问题标题】:How to use python selenium to click this element with text bb1如何使用 python selenium 单击带有文本 bb1 的元素
【发布时间】:2021-01-09 13:54:42
【问题描述】:
<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()

【问题讨论】:

标签: python selenium xpath youtube css-selectors


【解决方案1】:

要点击文本为 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
    

参考文献

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

【讨论】:

    猜你喜欢
    • 2016-02-19
    • 1970-01-01
    • 2021-03-31
    • 1970-01-01
    • 1970-01-01
    • 2017-11-23
    • 1970-01-01
    • 2019-10-23
    相关资源
    最近更新 更多