Javascript 如何(通过URL)获取给定HTML文档或网页中特定HTML元素的值?
我想将包含Javascript 如何(通过URL)获取给定HTML文档或网页中特定HTML元素的值?,javascript,html,wpf,web,getelementbyid,Javascript,Html,Wpf,Web,Getelementbyid,我想将包含值标记的网页的url传递给setTextBoxText(字符串url,字符串id)等方法,该方法写入wpf应用程序codeBehind(MainWindow.xaml.cs)中,并将特定文本框控件的文本设置为span值,而不加载网页。(例如,亚马逊产品的跟踪价格) 我更喜欢执行JavaScript代码来获取html元素的值,并将wpf控件的内容设置为js代码的结果(函数) 大概是这样的: public partial class MainWindow : Window { st
值
标记的网页的url传递给setTextBoxText(字符串url,字符串id)
等方法,该方法写入wpf应用程序codeBehind(MainWindow.xaml.cs
)中,并将特定文本框
控件的文本设置为span值,而不加载网页。(例如,亚马逊产品的跟踪价格)
我更喜欢执行JavaScript代码来获取html元素的值,并将wpf控件的内容设置为js代码的结果(函数)
大概是这样的:
public partial class MainWindow : Window
{
string url = "https://websiteaddress.com/rest";
setTextBoxText(url, "spanID");
static void setTextBoxText(string url, string id)
{
// code to get document by given url
txtPrice.Text = getHtmlElementValue(id);
}
string getHtmlElementValue(string id)
{
// what code should be written here?
// any combination of js and c#?
// var result = document.getElementById(id).textContent;
// return result;
}
}
您可以使用加载URL的HTML内容,然后通过将响应包装到mshtml中,以类似JavaScript的语法处理DOM对象。HTMLDocument
-需要引用Microsoft.mshtml.dll:
如何知道文档是否已完全加载?此行:
返回此.HtmlDocument.getElementById(elementId).innerText代码>抛出System.NullReferenceException:“对象引用未设置为对象的实例。”我最初发布了另一个实现。我重构了这个解决方案,忘记了调整方法类型。我已经修复了UpdateHtmlDocumentAsync
的返回类型。这也是用于加载HTML文档的方法。您必须等待此方法。当UpdateHtmlDocumentAsync
返回时,将加载文档(分配给属性HtmlDocument
)并准备进行处理。在GetHtmlElementValueById
内引发此异常的位置?代码对我有用this.HtmlDocument
如果URL无法解析,则会返回null
。抱歉,我想我可能是无意中观察到了错误的事件。我已将代码改为观察WebBrowser.LoadCompleted
事件。这将修复您的异常。GetHtmlElementValueById中的Yes。但我输入的url是一个有效的网页!
private mshtml.HTMLDocument HtmlDocument { get; set; }
private async Task SetTextBoxTextAsync(string url, string id)
{
await UpdateHtmlDocumentAsync(url);
var value = GetHtmlElementValueById(id);
txtPrice.Text = value;
}
public async Task UpdateHtmlDocumentAsync(string url)
{
using (HttpClient httpClient = new HttpClient())
{
byte[] response = await httpClient.GetByteArrayAsync(url);
string httpResponseText = Encoding.GetEncoding("utf-8").GetString(response, 0, response.Length - 1);
string htmlContent = WebUtility.HtmlDecode(httpResponseText);
this.HtmlDocument = new HTMLDocument();
(this.HtmlDocument as IHTMLDocument2).write(htmlContent);
}
}
public string GetHtmlElementValueById(string elementId)
=> this.HtmlDocument.getElementById(elementId).innerText;