在路径上设置 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
最佳答案
以下 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/