简体   繁体   中英

Selenium button click in Python

Im coding a selenium bot with Python which will be watching videos on different websites. I need it to press button to play video, but it doesnt work. I use Chrome webdriver and tried to use undetected_chromedriver, but nothing changed.

My webdriver:

browser = webdriver.Chrome(ChromeDriverManager().install())

or

browser = undetected_chromedriver.Chrome()

My code is:

sendContinue = browser.find_element(By.XPATH,'/html/body/table/tbody/tr[1]/td/table/tbody/tr[2]/td[2]/a').click()

It worked on login page, but not here.

Button element:

<button class="ytp-large-play-button ytp-button ytp-large-play-button-red-bg" aria-label="Смотреть"><svg height="100%" version="1.1" viewBox="0 0 68 48" width="100%"><path class="ytp-large-play-button-bg" d="M66.52,7.74c-0.78-2.93-2.49-5.41-5.42-6.19C55.79,.13,34,0,34,0S12.21,.13,6.9,1.55 C3.97,2.33,2.27,4.81,1.48,7.74C0.06,13.05,0,24,0,24s0.06,10.95,1.48,16.26c0.78,2.93,2.49,5.41,5.42,6.19 C12.21,47.87,34,48,34,48s21.79-0.13,27.1-1.55c2.93-0.78,4.64-3.26,5.42-6.19C67.94,34.95,68,24,68,24S67.94,13.05,66.52,7.74z" fill="#f00"></path><path d="M 45,24 27,14 27,34" fill="#fff"></path></svg></button>

Can anyone solve this?

These kind of XPATH are unreliable, could you try the following?

sendContinue = browser.find_element(By.XPATH,"//*[@class='.ytp-large-play-button.ytp-button']").click()

Off topic, but it sometimes help to wait for the button to appear, like:

def wait_click(driver, xpath, delay = 20):
    try:
        myElem = WebDriverWait(driver, delay).until(EC.presence_of_element_located((By.XPATH, xpath)))
        myElem.click()
        return myElem
    except TimeoutException:
        print("Loading took too much time!")

You can call it with:

wait_click(driver, "//*[@class='.ytp-large-play-button.ytp-button.ytp-large-play-button-red-bg']")

To interact with any clickable element ideally 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(browser, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button.ytp-large-play-button.ytp-button.ytp-large-play-button-red-bg[aria-label='Смотреть'] > svg > path"))).click()
  • Using XPATH :

     WebDriverWait(browser, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[@class='ytp-large-play-button ytp-button ytp-large-play-button-red-bg' and @aria-label='Смотреть']"))).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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM