提问人:Doug 提问时间:7/21/2023 更新时间:7/21/2023 访问量:49
如何使用 HTMLAgilityPack 和 C 从动态表中抓取数据#
How can I scrape data from a dynamic table using HTMLAgilityPack and C#
问:
在过去的几天里,我一直在尝试多种方法从表中提取数据:
网站链接。
这是我在网上找到并改编的一个代码版本。 我尝试了许多方法,不确定 Xpath 是否正确或问题发生在哪里:
private void button26_Click(object sender, EventArgs e)
{
//BCFERRIES 2
// URL of the website containing the table
string url = "https://www.bcferries.com/current-conditions/SWB-TSA/";
// Load the HTML content from the URL
HtmlWeb web = new HtmlWeb();
HtmlAgilityPack.HtmlDocument doc = web.Load(url);
//string tableXPath = "//table[@class='table-class']";
//string tableXPath = "//*[@id=\"tabs-1\"]/div[1]/table";
//string tableXPath ="/html/body/main/section[6]/div[1]/div/div[5]/div[1]/div[1]/table";
//string tableXPath = "//*[@id=\"tabs-1\"]";
//*[@id="tabs-1"]/div[1]/table/tbody
//string tableXPath = "//div[@id='tabs-1']/div[1]/table";
string tableXPath = "//div[@id='tabs']";
// Get the table from the HTML document
HtmlNode tableNode = doc.DocumentNode.SelectSingleNode(tableXPath);
//TEST
//HtmlNode firstChild = tableNode.FirstChild;
//HtmlNode firstChild = tableNode.LastChild;
//HtmlNode firstChild = tableNode.NextSibling;
//MessageBox.Show(firstChild.OuterHtml);
//MessageBox.Show(firstChild.InnerHtml);
// Check if the table exists
if (tableNode != null)
{
// Get all rows in the table
//var rows = tableNode.SelectNodes(".//tr");
var rows = tableNode.SelectNodes("./tr");
// Iterate through each row and display the data
foreach (var row in rows)
{
//var cells = row.SelectNodes(".//td");
var cells = row.SelectNodes("./td");
if (cells != null)
{
foreach (var cell in cells)
{
richTextBox1.AppendText(cell.InnerText.Trim() + "\t");
//MessageBox.Show(cell.InnerText.Trim());
}
richTextBox1.AppendText("\n");
//MessageBox.Show("");
}
}
}
else
{
MessageBox.Show("Table not found on the website.");
}
}
每次我运行代码时,它要么找不到表,这取决于我使用的 Xpath(我用 Xpath 进行了许多尝试),要么如果它找到表,当我尝试查看第一个节点时,它会显示一个空白的消息框,然后程序在尝试读取第一行时失败。
任何帮助将不胜感激......我正在尝试在构建用于存储数据的数组或列表之前查看是否可以读取任何时间、船或状态字段。
谢谢 道格
答:
0赞
Danil Alekseevich
7/21/2023
#1
通过浏览器和代码链接的响应是不同的。所以我试图从表格中删除最后一个斜杠并收到结果。string url = "https://www.bcferries.com/current-conditions/SWB-TSA/";
评论
0赞
Doug
7/21/2023
好的,谢谢丹尼尔。您使用什么 Xpath 来访问该表?
0赞
Danil Alekseevich
7/21/2023
'.SelectNodes(“//表”)'
评论