首页 > 解决方案 > 如何使用 GeckoFX 60 的评估脚本方法获取 youtube 视频的上传日期?

问题描述

我在 WPF 中使用的 GeckoFX 60 浏览器有一个评估脚本方法,它接受 javascript 代码(以字符串的形式)。

我做了什么:

  1. 寻找一个 YouTube 视频来测试我的 javascript 代码
  2. 放置document.getElementById('date').innerText在控制台上给了我需要的信息
  3. 回到我的 WPF 应用程序并放置:

(C#)

string videoDate = "";
using (Gecko.AutoJSContext js = new Gecko.AutoJSContext(YouTubeBrowser.Window))
{
    js.EvaluateScript("document.getElementById('date').innerText", out videoDate);
}
NewProject.VideoDate = DateTime.Parse(videoDate);

问题:

它正在捕获一个错误,所以我在解析字符串之前放置了一个中断,发现 videoDate 字符串为空

我所期望的:

我希望它返回•Jan 30, 2008我在浏览器上输入 js 代码时显示的控制台。

到目前为止,当从 YouTube 视频中获取其他信息时,这些代码行对我有用(在控制台和我的 wpf 应用程序的 GeckoBrowser 上):

js.EvaluateScript("document.title", out videoTitle);= 获取视频标题

js.EvaluateScript("document.URL", out videoId);= 获取视频 URL(然后我将其过滤掉以仅获取 c# 中的视频 ID)

我尝试过的其他一些方法不起作用:

A. 使用 GeckoElement 并检索浏览器的 Document 及其 textContent

GeckoElement elem = YouTubeBrowser.Document.GetElementById("date");
videoDate = elem.textContent;

B. 使用 GeckoElement 并检索浏览器的 DomDocument 及其 textContent

GeckoElement elem = YouTubeBrowser.DOMDocument.GetElementById("date");
videoDate = elem.textContent;

C. 将 innerText 更改为 textContent (基于另一个 SO 答案,我看到说 firefox 不理解 innerText (这很奇怪,因为它在控制台上工作,但我猜他们稍后添加了对它的支持)而是使用 textContent 来检索价值)

string videoDate = "";
using (Gecko.AutoJSContext js = new Gecko.AutoJSContext(YouTubeBrowser.Window))
{
    js.EvaluateScript("document.getElementById('date').textContent", out videoDate);
}
NewProject.VideoDate = DateTime.Parse(videoDate);

标签: c#geckofx

解决方案


我认为这与 YouTube 上的动态 DOM 有关。
虽然我无法按元素 ID 检索值,但我在另一个标签上按类名找到了相同的信息:

_gfxBrowser.Document.GetElementsByClassName("watch-time-text")[0].TextContent

回报:"Published on Jan 25, 2019"


推荐阅读