Chrome Python中的Selenium按钮单击

yjghlzjz  于 2023-01-15  发布在  Go
关注(0)|答案(2)|浏览(161)

我正在用Python编写一个 selenium 机器人,它可以在不同的网站上观看视频。我需要它按下按钮播放视频,但它不起作用。我使用Chrome webdriver,并试图使用undetected_chromedriver,但没有任何变化。

我的Web驱动程序:

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

browser = undetected_chromedriver.Chrome()

我的密码是:

sendContinue = browser.find_element(By.XPATH,'/html/body/table/tbody/tr[1]/td/table/tbody/tr[2]/td[2]/a').click()
工作在登录页面上,但不是在这里。

按钮元素:

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

有人能解决这个问题吗?

jq6vz3qz

jq6vz3qz1#

这类XPATH不可靠,您可以尝试以下方法吗?

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

离题,但有时候等待按钮出现会有所帮助,例如:

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!")

您可以使用以下命令调用它:

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

qzwqbdag2#

要与任何***可单击***元素交互,理想情况下需要为element_to_be_clickable()引入WebDriverWait,并且可以使用以下locator strategies之一:

  • 使用 *CSS选择器 *:
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()
  • 使用 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()

*注意:您必须添加以下导入:

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

相关问题