【发布时间】:2017-12-09 04:35:35
【问题描述】:
我有一个带有文本框的 Windows 窗体,该代码假设使用我通过 chromes 开发人员工具获得的 xpath 从网站中提取信息并将其显示在所述文本框中。
问题是当我运行程序时,文本框中没有显示任何内容。我不确定用于获取信息的代码是否错误,或者我用于显示所述信息的代码是否错误。请注意此代码使用 HtmlAgilityPack。
这里是有问题的代码:
private void richTextBox1_TextChanged(object sender, EventArgs e)
{
string Url = "https://apps.ko.com/aami/iguest/default.asp";
HtmlWeb web = new HtmlWeb();
HtmlAgilityPack.HtmlDocument doc = web.Load(Url);
string username = doc.DocumentNode.SelectNodes("/html/body/center/div/table/tr[1]/td[2]/strong")[0].InnerText;
string password = doc.DocumentNode.SelectNodes("/html/body/center/div/table/tr[2]/td[2]/strong")[0].InnerText;
string summary = doc.DocumentNode.SelectNodes("/html/body/center/div/table/tr[4]")[0].InnerText;
richTextBox1.Text = "User Name: " + username + " | Password: " + password + " | Summary: " + summary;
}
在内网页面上列出了一个用户名和密码,我正在尝试从网页中提取它并在文本框中显示它,只要这个应用程序在域机器上运行它应该能够访问页面并显示所需信息。我没有尝试登录任何东西,只是从网页中提取一些文本。
没有人可以看到该页面,因为您不在只能访问该页面的域中。
这里是 HTML 页面,出于安全原因,代码中的网址已更改。
<body>
<div style="background-image:url(intranet.com/images/headergraphic_repeat_tile.jpg); background-repeat:repeat-x; margin-top:0px; margin-left:0px; width:100%; height:118px; padding:0px;">
<img src="https://intranet.com/iguest/images/headergraphic_extended.jpg" align="right">
</div>
<center>
<div style="width:390px; padding:20px; ">
<h2 align="center">Guest Wireless Access</h2>
<p align="left">Guests may access the wireless service by using the log-in <br>credentials below. <br>
<br>
</p>
<table width="360" align="left" cellpadding="4" cellspacing="0">
<tbody><tr>
<td width="63">User ID:</td>
<td><strong>KOGUEST</strong></td>
</tr>
<tr>
<td>Password:</td>
<td><strong><span id="iguestpw">P@ssword</span></strong> <font size="-2"> (Password is case-sensitive.)</font></td>
</tr>
<tr>
<td colspan="2" align="center"><font size="-2"> The password is updated once a week on<br> Saturday at midnight EST.<br></font></td>
</tr>
<tr>
<td colspan="2"><br><br><p align="left"><a href="https://partner.intranet.com/sites/kooffice/training/documentation/guest wireless access_instructions for connecting.doc" target="_blank">Print instructions</a> for your guest.<!-- or <a href="https://partner.intranet.com/sites/kooffice/training/i want to/courtesy wireless access.aspx" target="_blank">visit DWP</a> to learn more.--></p></td>
</tr>
</tbody></table>
</div>
</center>
</body>
【问题讨论】:
-
使用该 Html,您的 xpath 将丢失
tbody。在table标签内,有一个tbody标签,表格的行在tbody内。例如,第一个 xpath 应该是/html/body/center/div/table/tbody/tr[1]/td[2]/strong -
我读到了一些错误地添加了 tbody 的地方,但是我使用 chrome 得到了那个 xpath,所以它可能是错误的,我不知道如何编写我自己的 xpath
-
在 Firefox 中,您右键单击一个元素,然后按“检查”。然后右键单击 Html 标签并复制 xpath。您还可以使用 $x("my xpath here") 在控制台中缩短和测试 xpath。这个想法是写像
//td[text()='User ID:']/following-sibling::td/strong这样的东西而不是完整路径。注意开头的双斜杠//。有了这个,它会在任何地方找到它。 Chrome 检查工具也不错。
标签: c# xpath visual-studio-2017 richtextbox html-agility-pack