Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
61 views
in Technique[技术] by (71.8m points)

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()
question from:https://stackoverflow.com/questions/65643446/how-to-use-python-selenium-to-click-this-element-with-text-bb1

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...