在python中使用Selenium查找特定标签

问题描述

我正在尝试使用硒达到youtube订阅按钮,然后单击它。

enter image description here

我已经尝试了一切,find_by_class,find_by_tagname等。 这是我使用的语法:

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']
,

使用 browser.find_element_by_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”。不管文本当前是“ Subscribe”还是“ Subscribed”,这都应该起作用,因为它使用@id。