Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/363.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 无法使用xpath获取youtube视频的持续时间_Python_Xpath_Lxml - Fatal编程技术网

Python 无法使用xpath获取youtube视频的持续时间

Python 无法使用xpath获取youtube视频的持续时间,python,xpath,lxml,Python,Xpath,Lxml,我想写一些东西,可以让我得到youtube链接的视频持续时间。所以我找到了请求和lxml,并开始遵循指南 以下是设置: import requests from lxml import html url = 'https://www.youtube.com/watch?v=EN8fNb6uhns' page = requests.get(url) tree = html.fromstring(page.content) 然后我尝试使用xpath获取持续时间,但它不起作用。正在尝试获取持续时间

我想写一些东西,可以让我得到youtube链接的视频持续时间。所以我找到了
请求
lxml
,并开始遵循指南

以下是设置:

import requests
from lxml import html

url = 'https://www.youtube.com/watch?v=EN8fNb6uhns'
page = requests.get(url)
tree = html.fromstring(page.content)
然后我尝试使用xpath获取持续时间,但它不起作用。正在尝试获取持续时间:

tree.xpath('//span[@class="ytp-time-duration"]/text()')
返回一个空列表。但当我尝试获得标题(作为测试)时:

它起作用了。使用inspect复制duration元素的xpath时,不会返回任何内容:

tree.xpath('/html/body/div[2]/div[4]/div/div[4]/div[2]/div[2]/div/div[24]/div[2]/div[1]/div/span[3]')
当我对标题做同样的操作时,它再次起作用

发生了什么事

span[@class="ytp-time-duration"]

这个
span
标记是由JavaScript生成的,它不会由
请求返回,
请求
只返回HTML代码

对于YouTube,Xpath不一致。 我有两个不同的XPath(这是我用来捕获视频持续时间的两个XPath)

尝试了按类名查找元素的选项

FindElement(By.ClassName("ytp-time-duration"))
这一直有效。

string VideoDuration = firfxdrivr.FindElement(By.ClassName("ytp-time-duration")).GetAttribute("textContent");

Console.WriteLine(VideoDuration);

输出:19:18

解决您问题的一个方法可能是无头浏览器或类似PhantomJS的webkit,它可以执行JS。
FindElement(By.ClassName("ytp-time-duration"))
string VideoDuration = firfxdrivr.FindElement(By.ClassName("ytp-time-duration")).GetAttribute("textContent");

Console.WriteLine(VideoDuration);