如何解决如何获取给定HTML文档或网页中特定HTML元素的值通过URL?
我想将包含<span id="spanID"> value </span>
标记的网页的网址传递给setTextBoxText(string url,string id)
这样的方法,该方法以wpf应用程序codeBehind(MainWindow.xaml.cs
)编写,并设置特定的TextBox
控制范围值,而无需加载网页。 (例如,用于跟踪亚马逊产品的价格)
我更喜欢执行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;
}
}
解决方法
您可以使用HttpClient
来加载URL的HTML内容,然后通过将响应包装到mshtml.HTMLDocument
中,以类似JavaScript的语法处理DOM对象-需要参考 Microsoft .mshtml.dll :
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,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;
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。