c# - 使用 C# 和 HTMLAgility 抓取网页

标签 c# .net web-scraping html-agility-pack data-mining

我读过 HTMLAgility 1.4是抓取网页的一个很好的解决方案。作为一名新程序员,我希望我能对这个项目有所投入。 我这样做是作为 C#申请表。我正在使用的页面非常简单。我需要的信息只停留在 2 个标签之间 <table class="data"></table> .

我的目标是提取 Part-Num 的数据, Manu-Number , Description , Manu-Country , Last Modified , Last Modified By , 出页面并将数据发送到SQL表。

一个转折点是还有一个小的 PNG还需要从 src="/partcode/number 中抓取的图片.

我没有任何完整的可用代码。我认为这段代码会告诉我我是否正朝着正确的方向前进。即使进入调试,我也看不到它有任何作用。有人可以指出我正确的方向吗?越详细越好,因为显然我还有很多东西要学。

谢谢你,我真的很感激。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HtmlAgilityPack;
using System.Xml;

namespace Stats
{
    class PartParser
    {
        static void Main(string[] args)
        {
            HtmlDocument doc = new HtmlDocument();
            doc.LoadHtml("http://localhost");
            //My understanding this reads the entire page in?
            var tables = doc.DocumentNode.SelectNodes("//table");
            // I assume that this sets up the search for words containing table
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
            Console.WriteLine(ex.StackTrace);
            Console.ReadKey();    
        }
    }
}

网页代码是:

<!DOCTYPE html 
     PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    <head>
        <meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
        <title>Part Number Database: Item Record</title>
        <table class="data">
            <tr><td>Part-Num</td><td width="50"></td><td>
            <img src="/partcode/number/072140" alt="072140"/></td></tr>
            <tr><td>Manu-Number</td><td width="50"></td><td>
            <img src="/partcode/manu/00721408" alt="00721408" /></td></tr>    
            <tr><td>Description</td><td></td><td>Widget 3.5</td></tr>
            <tr><td>Manu-Country</td><td></td><td>United States</td></tr>    
            <tr><td>Last Modified</td><td></td><td>26 Jan 2009,  8:08 PM</td></tr>    
            <tr><td>Last Modified By</td><td></td><td>Manu</td></tr>
        </table>
    <head/>
</html>

最佳答案

开始部分关闭:

HtmlDocument doc = new HtmlDocument();
doc.LoadHtml("http://localhost");   

LoadHtml(html) 将 html 字符串加载到文档中,我认为您需要这样的东西:

HtmlWeb htmlWeb = new HtmlWeb();
HtmlDocument doc  = htmlWeb.Load("http://stackoverflow.com");

关于c# - 使用 C# 和 HTMLAgility 抓取网页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5320231/

相关文章:

c# - CPU使用率在执行过程中变得非常高

javascript - RxJS 中的 Rx.Observable.ForkJoin 和并行异步(使用 X-Ray)

python - 我的脚本在应该异步运行时遇到错误

.net - 窗体转图片

c# - 笛卡尔积或 2 个大文本文件的最佳方法

python - 网页抓取帮助

c# - json.net 有关键方法吗?

c# - C# 服务器(不是 Web 服务器)和 PHP 之间的数据交换

c# - Web API 的缓存策略

c# - 使用 LINQ 将字符串转换为 int 以进行排序