python - 在 Python 中使用 Selenium 查找 YouTube 视频中评论数量的 CSS 选择器应该是什么?

标签 python selenium youtube css-selectors

在路径上设置 chromedriver 并粘贴搜索的 URL:

driver = webdriver.Chrome('**************') 
driver.get("https://www.youtube.com/results?search_query=youtube+keywords&sp=EgIQAQ%253D%253D")

检索视频链接:

user_data = driver.find_elements_by_xpath('//*[@id="video-title"]') <br>
links = []<br>
for i in user_data:<br>
            links.append(i.get_attribute('href'))

使用我们将收集的新信息创建一个新的 df:

df = pd.DataFrame(columns = ['v_search', 'v_id','v_comments'])

使用 Selenium 查找剩余数据:

wait = WebDriverWait(driver, 10)
v_search = "Youtube Keyword" 
for x in links[:1]:<br>
        driver.get(x)<br>
        v_id = x.strip('https://www.youtube.com/watch?v=') 

        ### HERE IS MY QUESTION.
        v_comments = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "#count > yt-formatted-string"))).text

        # Throw information in the dataframe we defined before (fills row per row).
        df.loc[len(df)] = [v_search,v_id,v_comments]
        sleep(0.5)    #in seconds

Snapshot of the whole code

Traceback error

最佳答案

以下 CSS 选择器对我有用:

#count>.count-text.style-scope.ytd-comments-header-renderer

测试如下:

document.querySelector("#count>.count-text.style-scope.ytd-comments-header-renderer").innerHTML;

结果将类似于 -- x Comments。

PS:最好使用 visibility_of_element_ located 预期条件。因此,就您而言,它将是:

from selenium.webdriver.common.keys import Keys


...
driver.find_element_by_tag_name("body").send_keys(Keys.PAGE_DOWN)
v_comments = wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, "#count>.count-text.style-scope.ytd-comments-header-renderer"))).text

希望对你有帮助!

关于python - 在 Python 中使用 Selenium 查找 YouTube 视频中评论数量的 CSS 选择器应该是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61410776/

相关文章:

python - 使用 scipy 进行二维插值/平滑线时如何提高性能?

python - find_element_by_class_name 类空间不起作用

selenium - Jenkins-selenium webdriver-chrome 驱动程序

java - 正则表达式 YouTube IFRAME

python - 沿指定轴的两个 3D 矩阵之间的 np.dot 乘积

python - 是否可以通过 django-nonrel/Google App Engine 中的主键获取对象?

css - Selenium IDE - 验证类的值

android - 是否可以在 youtube 播放器 API 上播放非 youtube 视频?

json - 播放列表项数超过100时,检索YouTube播放列表错误

python - 如何向量化这两个嵌套的 for 循环?