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

What should be the CSS Selector to find count of comments in a YouTube video using Selenium in Python?

在路径上设置 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

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 评论。

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

希望对你有所帮助!

使用 Google Chrome 你可以使用 'inspect' 模式获取 XPATH,见下图:

这给了我 XPATH:

//*[@id="count"]/yt-formatted-string

所以:

lol = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, '//*[@id="count"]/yt-formatted-string')))
print (lol.text)

好的,所以我想通了如果有人遇到 selenium 的同时异常错误可能是什么问题。我认为硒的工作方式如下。驱动程序打开一个网站并查找您要查找的元素。在我的例子中,它是对 YouTube 视频的评论数。如果您的元素在您看不到的页面下方,则硒可能无法拾取它。所以,我所做的是让驱动程序滚动到页面底部,等待几秒钟以便加载。虽然这对某些人来说可能就足够了,但在某些情况下我仍然遇到一些问题。所以我也让它上升到 300(我假设屏幕像素大小)并等待它加载。如果这仍然不适合您,请考虑让 selenium 在加载时移动鼠标,这可能会触发加载。

# we will make it rest for 5 seconds
SCROLL_PAUSE_TIME = 0.5
# scroll to the bottom 
driver.execute_script("window.scrollTo(0, 1080)") 
# Wait to load page
time.sleep(SCROLL_PAUSE_TIME)
# scroll to the bottom 
driver.execute_script("window.scrollTo(300, 1080)") 
# Wait to load page
time.sleep(SCROLL_PAUSE_TIME)

此外,打开驱动程序 window 这样您就可以看到它的神奇之处。这也可能使它提取信息。希望这可以帮助。我很高兴能弄明白。