Python 3.x 在python中使用selenium查找特定标记

Python 3.x 在python中使用selenium查找特定标记,python-3.x,selenium,webautomation,Python 3.x,Selenium,Webautomation,我正在尝试使用selenium访问youtube订阅按钮,然后单击它。 我尝试了所有方法,按类查找,按标记名查找等等。 这是我正在使用的语法: subscribe_button = driver.find_element_by_class_name('style-scope ytd-subscribe-button-renderer') subscribe_button.click() 我尝试使用xpath,但失败了。 那么,一旦我进入youtube上任何频道的频道页面,我如何才能到达该按钮

我正在尝试使用selenium访问youtube订阅按钮,然后单击它。

我尝试了所有方法,按类查找,按标记名查找等等。 这是我正在使用的语法:

subscribe_button = driver.find_element_by_class_name('style-scope ytd-subscribe-button-renderer')
subscribe_button.click()
我尝试使用xpath,但失败了。
那么,一旦我进入youtube上任何频道的频道页面,我如何才能到达该按钮呢?

如果我想使用标签的属性访问标签,我该怎么做呢?

您可以尝试下面的xpath:

//*[@id='subscribe-button' and @class='style-scope ytd-video-secondary-info-renderer']//*[text()='Subscribed']

您可以尝试以下xpath:

//*[@id='subscribe-button' and @class='style-scope ytd-video-secondary-info-renderer']//*[text()='Subscribed']

使用浏览器的解决方案。通过xpath()查找元素:

# Press subscribe button on youtube channel

from selenium import webdriver
from selenium.webdriver.firefox.options import Options

URL = "https://www.youtube.com/c/MedlifeCrisis"

# Browser options
options = Options()
options.headless = True
firefox_profile = webdriver.FirefoxProfile()
firefox_profile.set_preference("browser.privatebrowsing.autostart", True)

browser = webdriver.Firefox(firefox_profile=firefox_profile)
browser.get(URL)

try:
    browser.find_element_by_xpath('//div[@id="subscribe-button"]').click() # Click subscribe button
    print("Pressed subscribe button.")
except:
    print("Subscribe button not found")

唯一棘手的是“按钮”实际上是一个“div”。无论文本当前是“订阅”还是“订阅”,这都应该有效,因为它使用@id。

使用浏览器的解决方案。通过xpath()查找\u元素\u

# Press subscribe button on youtube channel

from selenium import webdriver
from selenium.webdriver.firefox.options import Options

URL = "https://www.youtube.com/c/MedlifeCrisis"

# Browser options
options = Options()
options.headless = True
firefox_profile = webdriver.FirefoxProfile()
firefox_profile.set_preference("browser.privatebrowsing.autostart", True)

browser = webdriver.Firefox(firefox_profile=firefox_profile)
browser.get(URL)

try:
    browser.find_element_by_xpath('//div[@id="subscribe-button"]').click() # Click subscribe button
    print("Pressed subscribe button.")
except:
    print("Subscribe button not found")

唯一棘手的是“按钮”实际上是一个“div”。无论文本当前是“订阅”还是“订阅”,这都应该有效,因为它使用@id。

请将DOM粘贴为文本,而不是屏幕截图。此xpath可能有效://*[包含(@class,'ytd Subscribe button renderer')]/*[包含(@class,'ytd-Subscribe-button-renderer')和文本()='Subscribed']请将DOM粘贴为文本,不是截图。此xpath可能有效://*[包含(@class,'ytd subscribe-button-renderer')]/*[包含(@class,'ytd-subscribe-button-renderer')和text()='Subscribed']