如何使用 python selenium 单击带有文本 bb1 的元素

问题描述 投票:0回答:1
<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-webdriver xpath youtube css-selectors
1个回答
0
投票

要单击文本为 bb1 的元素,您可以使用以下任一定位器策略

  • 使用

    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()
    

理想情况下,要单击需要为 element_to_be_clickable() 引发

WebDriverWait
的元素,您可以使用以下任一定位器策略

  • 使用

    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
    

参考文献

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

© www.soinside.com 2019 - 2024. All rights reserved.