如何通过 Selenium 和 Python 使用用户代理在 youtube 评论中单击 youtube 链接 [英] How to click youtube link within youtube comment using an user agent through Selenium and Python

查看:51
本文介绍了如何通过 Selenium 和 Python 使用用户代理在 youtube 评论中单击 youtube 链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习 python selenium,我想点击 youtube 评论中的 youtube 链接,有人可以帮助我吗?

I'm learning about python selenium, I want to click a youtube link in the youtube comment, can someone help me?

示例:URL

HTML:

<a class="yt-simple-endpoint style-scope yt-formatted-string" spellcheck="false" href="/watch?v=PbLtyVcMrk0">https://www.youtube.com/watch?v=PbLtyVcMrk0&#65279;</a>

代码试验:

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

ua = UserAgent()
options = webdriver.ChromeOptions()
userAgent = ua.random
print(userAgent)
options.add_argument('user-agent={userAgent}')
driver = webdriver.Chrome(chrome_options=options)
driver.get("https://www.youtube.com/watch?v=NIWwJbo-9_8&lc=UgwNBxYVXb6uiVTioPB4AaABAg")
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//a[@class='yt-uix-sessionlink  ' and contains(@href, '/watch?v=PbLtyVcMrk0')]"))).click()

推荐答案

你们已经很接近了.单击文本为 https://www.youtube.com/的所需评论watch?v=PbLtyVcMrk0url 中 您需要引入 WebDriverWait 以使 元素可点击,您可以通过 Selenium 和 Python 使用 useragent 使用以下解决方案:

You were pretty close. To click on the desired comment with text as https://www.youtube.com/watch?v=PbLtyVcMrk0 within the url you need to induce WebDriverWait for the element to be clickable and you can use the following solution using useragent through Selenium and Python:

  • 代码块:

  • Code Block:

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

ua = UserAgent()
options = webdriver.ChromeOptions()
userAgent = ua.random
print(userAgent)
options.add_argument('user-agent=' + userAgent)
driver = webdriver.Chrome(chrome_options=options)
driver.get("https://www.youtube.com/watch?v=NIWwJbo-9_8&lc=UgwNBxYVXb6uiVTioPB4AaABAg")
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//a[@class='yt-uix-sessionlink       spf-link ' and contains(@href, '/watch?v=PbLtyVcMrk0')]"))).click()

  • 控制台输出:

  • Console Output:

    Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2049.0 Safari/537.36
    

  • 这篇关于如何通过 Selenium 和 Python 使用用户代理在 youtube 评论中单击 youtube 链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆