Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/selenium/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在抓取youtube时找不到元素_Python_Selenium_Web Scraping - Fatal编程技术网

Python 在抓取youtube时找不到元素

Python 在抓取youtube时找不到元素,python,selenium,web-scraping,Python,Selenium,Web Scraping,我正试图从任何视频链接中获取youtube视图。我尝试使用selenium驱动程序捕获元素,但由于某些原因无法捕获。下面是我使用的代码: driver=webdriver.chrome() driver.get("https://www.youtube.com/watch?v=F-eMt3SrfFU") driver.find_element_by_id("count").text driver.find_element_by_id("watch-view-count").text 我无法捕获

我正试图从任何视频链接中获取youtube视图。我尝试使用selenium驱动程序捕获元素,但由于某些原因无法捕获。下面是我使用的代码:

driver=webdriver.chrome()
driver.get("https://www.youtube.com/watch?v=F-eMt3SrfFU")
driver.find_element_by_id("count").text
driver.find_element_by_id("watch-view-count").text
我无法捕获此链接上的元素。我做错什么了吗?
这是一个youtube电影链接,我想在该链接上获取视图。可能在get()元素无法立即使用之后,情况就不一样了。您可以像下面的示例一样使用等待

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.chrome()
driver.get("https://www.youtube.com/watch?v=F-eMt3SrfFU")
element = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, "count"))) # 10 seconds implicit wait
print element.text 

我建议您稍微细化一点,而不是使用
id(“count”)
将节点作为目标,我们可以将innerHTML作为目标,即
标记,如下所示:

from selenium import webdriver

driver=webdriver.Chrome(executable_path=r'C:\Utility\BrowserDrivers\chromedriver.exe')
driver.get("https://www.youtube.com/watch?v=F-eMt3SrfFU")
my_views = driver.find_element_by_xpath("//span[@class='view-count style-scope yt-view-count-renderer']").text
print(my_views)

我不知道为什么id=count不起作用。可能与yt view count渲染器标记有一些奇怪的交互。我测试了CSS选择器,
span.view count
,效果很好

顺便说一句,您可以在Chrome的devtools中使用
$$()
测试CSS选择器,例如
$$(“span.view count”)
$$()
大致相当于
驱动程序。通过css\u选择器()查找元素

有关此命令和其他命令的更多详细信息,请使用devtools,请参阅