如何用Selenium发表Youtube评论

时间:2015-02-01 19:11:49

标签: python selenium selenium-webdriver youtube

我正在尝试使用Selenium发布Youtube评论。以下是代码的要点(省略了关于登录Google的行):

comment_url = "https://www.youtube.com/all_comments?v=LAr6oAKieHk"
profile = webdriver.FirefoxProfile()
driver = webdriver.Firefox(firefox_profile=profile)

driver.get(comment_url)
assert "All comments" in driver.title

textbox = driver.find_element_by_class_name("box")
textbox.click()
textbox.send_keys("My comment")

textbox.click()按预期工作,并将焦点设置到评论框。但是,textbox.send_keys("My comment")不会将文本输入框中,但会以某种方式偏离焦点。

有人可以提出任何建议吗?谢谢!

1 个答案:

答案 0 :(得分:4)

首先,您需要单击该框以使其可编辑。然后,switch to the appropriate iframeset the innerHTML attribute基础"文本框"。您还必须在整个代码中使用Explicit Waits,因为youtube大量使用AJAX,并且每个操作都会发生异步动态DOM更新:

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

comment = 'test'

box = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CLASS_NAME, "box")))
box.click()

frame = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, '//iframe[@title="+1"]')))
driver.switch_to.frame(frame)

driver.find_element_by_xpath('//div[@onclick]').click()

element = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, '//div[@jsname="msEQQc"]/following-sibling::div//div[@g_editable="true"]')))
driver.execute_script("arguments[0].innerHTML='%s';" % comment, element)

完整代码(包括身份验证):

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


driver = webdriver.Firefox()
driver.get('https://accounts.google.com/ServiceLogin?continue=https%3A%2F%2Fwww.youtube.com%2Fsignin%3Fhl%3Den%26feature%3Dcomment%26app%3Ddesktop%26next%3D%252Fall_comments%253Fv%253DLAr6oAKieHk%26action_handle_signin%3Dtrue&uilel=3&service=youtube&passive=true&hl=en')

# log in
driver.find_element_by_id('Email').send_keys('username')
driver.find_element_by_id('Passwd').send_keys('password')
driver.find_element_by_id('signIn').click()

# post a comment
comment = "test"

box = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CLASS_NAME, "box")))
box.click()

frame = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, '//iframe[@title="+1"]')))
driver.switch_to.frame(frame)

driver.find_element_by_xpath('//div[@onclick]').click()

element = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, '//div[@jsname="msEQQc"]/following-sibling::div//div[@g_editable="true"]')))
driver.execute_script("arguments[0].innerHTML='%s';" % comment, element)