Search code examples
pythonselenium-webdriverxpathyoutubecss-selectors

How to use python selenium to click this element with text bb1


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

below one is a dangerous find element by full x path because the index might change

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

Solution

  • To click on the element with text as bb1 you can use either of the following Locator Strategies:

    • Using css_selector:

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

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

    Ideally, to click on the element you need to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following Locator Strategies:

    • Using 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()
      
    • Using 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()
      
    • Note: You have to add the following imports :

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

    References

    You can find a couple of relevant detailed discussions in: