html 中抓取数据,.net中 网页抓取数据(提取html中的数据,提取table中的数据)...

方法一:

WebRequest request = WebRequest.Create("http://www.cftea.com/");  WebResponse response = request.GetResponse();

StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("gb2312"));

var contents = reader.ReadToEnd();

Console.WriteLine(StripHTML(contents));

reader.Close();

reader.Dispose();

response.Close();

Console.Read();

方法二:(抓取html中table里面的数据)

string html = @"

";

var strReg = @"(?is)(?<=

)";

List result = new List();

MatchCollection mc = Regex.Matches(html, strReg);

foreach (Match m in mc)

{

//result.Add(m.Value);

Console.WriteLine(m.Value);

}

方法三:

var htmlDocument = new HtmlDocument();

htmlDocument.LoadHtml(orgStr);

var tables = htmlDocument.DocumentNode.SelectNodes("//table");//xpath的写法

foreach (var table in tables)

{

foreach (var tr in table.SelectNodes("//tr"))

{

var collegeName = tr.SelectNodes("//td").Skip(1).FirstOrDefault().InnerText;

Console.WriteLine(collegeName);

}

}

相关的网址:

方法四:(对网页中table里面的数据提取)

#region http://www.gaokao.com/e/20120109/4f0a8e1773aa0.shtml

//var url = "http://www.gaokao.com/e/20120109/4f0a8e1773aa0.shtml";

//var url = "http://www.gaokao.com/e/20120109/4f0a8e1773aa0_2.shtml";

//var url = "http://www.gaokao.com/e/20120109/4f0a8e1773aa0_3.shtml";

//var url = "http://www.gaokao.com/e/20120109/4f0a8e1773aa0_4.shtml";

//var url = "http://www.gaokao.com/e/20120109/4f0a8e1773aa0_5.shtml";

//var url = "http://www.gaokao.com/e/20120109/4f0a8e1773aa0_6.shtml";

//var orgStr = ChinaEduSp.Crawl.HttpUtility.GetContentByUrl(url, "gb2312");

//var htmlDocument = new HtmlDocument();

//htmlDocument.LoadHtml(orgStr);

//var rows = htmlDocument.DocumentNode.SelectNodes("//table//tr");

//foreach (var item in rows)

//{

//    var pos = item.SelectSingleNode("td[1]").InnerText;

//    var school = item.SelectSingleNode("td[2]").InnerText;

//    var province = item.SelectSingleNode("td[3]").InnerText;

//    var type = item.SelectSingleNode("td[4]").InnerText;

//    var totalScore = item.SelectSingleNode("td[5]").InnerText;

//    var seq = db.RankingDescriptions.Count();

//    //Response.Write("名次:" + pos + " 学校名称:" + school + " 所在省份:" + province + " 类型:" + type + " 总分:" + totalScore + "/r/n");

//    //Response.Write("名次:" + pos + " 学校名称:" + school);

//    try

//    {

//        db.RankingDescriptions.Add(new RankingDescription

//        {

//            POS = Convert.ToInt32(pos),

//            SchoolName = school,

//            Province = province,

//            Area = province,

//            Type = type,

//            TotalScore = totalScore,

//            IsShow = true,

//            IsDelete = false,

//            RankId = 0,

//            Seq = seq

//        });

//        db.SaveChanges();

//        seq++;

//    }

//    catch (Exception ex)

//    {

//        string msg = ex.Message;

//    }

//}

#endregion

#region http://www.gaokao.com/e/20120109/4f0a914934baa_2.shtml             //var url = "http://www.gaokao.com/e/20120109/4f0a914934baa_2.shtml";             //var orgStr = ChinaEduSp.Crawl.HttpUtility.GetContentByUrl(url, "gb2312");             //var htmlDocument = new HtmlDocument();             //htmlDocument.LoadHtml(orgStr);             //var rows = htmlDocument.DocumentNode.SelectNodes("//table//tr//td//table//tr");             //foreach (var item in rows)             //{             //    var pos = item.SelectSingleNode("td[1]").InnerText;             //    var school = item.SelectSingleNode("td[2]").InnerText;             //    var province = item.SelectSingleNode("td[3]").InnerText;             //    var totalScore = item.SelectSingleNode("td[4]").InnerText;             //    var seq = db.RankingDescriptions.Count();             //    //Response.Write("名次:" + pos + " 学校名称:" + school + " 所在省份:" + province + " 总分:" + totalScore + "/r/n");             //    //Response.Write("名次:" + pos + " 学校名称:" + school);             //    try             //    {             //        db.RankingDescriptions.Add(new RankingDescription             //        {             //            POS = Convert.ToInt32(pos),             //            SchoolName = school,             //            Province = province,             //            Area = province,             //            TotalScore = totalScore,             //            IsShow = true,             //            IsDelete = false,             //            RankId = 0,             //            Seq = seq             //        });             //        db.SaveChanges();             //        seq++;             //    }             //    catch (Exception ex)             //    {             //        string msg = ex.Message;             //    }             //}             #endregion

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Python可以使用BeautifulSoup库来抓取HTMLtable数据。以下是一个简单的示例代码: ```python from bs4 import BeautifulSoup import requests url = 'http://example.com' response = requests.get(url) soup = BeautifulSoup(response.text, 'html.parser') table = soup.find('table') rows = table.find_all('tr') for row in rows: cells = row.find_all('td') for cell in cells: print(cell.text) ``` 这个代码会从指定的URL获取HTML内容,然后使用BeautifulSoup库来解析HTML。它会找到第一个table元素,并遍历其的所有行和单元格,打印出每个单元格的文本内容。你可以根据自己的需求修改代码来获取不同的数据。 ### 回答2: Python 是一种广泛应用于数据处理、网络爬虫等领域的编程语言,在实现数据抓取时也有很强的实用性。如果需要从 HTML 文档抓取表格数据,可以使用 Python 的 BeautifulSoup 库和 pandas 库进行处理。 首先需要安装 BeautifulSoup 和 pandas 库,可以使用 pip 进行安装。安装完成后,需要从 HTML 文档读取页面内容并转化为 BeautifulSoup 对象,代码如下: ``` import requests from bs4 import BeautifulSoup # 请求页面,并将页面内容转化为 BeautifulSoup 对象 url = 'http://www.example.com' response = requests.get(url) soup = BeautifulSoup(response.content, 'html.parser') ``` 通过 soup 对象就可以使用各种 BeautifulSoup 提供的方法对 HTML 文档进行解析和处理。对于表格数据,可以先通过 find 方法找到 table 标签,然后通过 find_all 方法找到其的所有 tr 和 td 标签,将它们封装成一个嵌套列表: ``` data = [] table = soup.find('table') rows = table.find_all('tr') for row in rows: cells = row.find_all('td') row_data = [] for cell in cells: row_data.append(cell.text) data.append(row_data) ``` 如果需要使用 pandas 进行数据处理,可以将嵌套列表转化成 DataFrame 对象: ``` import pandas as pd df = pd.DataFrame(data) ``` 这样就可以使用 pandas 提供的各种方法对表格数据进行分析和处理了。总的来说,Python 抓取 HTML 的表格数据主要有两个基本步骤:使用 BeautifulSoup 对象解析 HTML 文档,找到 table 标签并解析其的 tr 和 td 标签构造成嵌套列表,然后使用 pandas 将嵌套列表转化为 DataFrame 对象进行数据处理。 ### 回答3: Python是一种高级编程语言,具有良好的可读性和易于学习的特点,因此越来越受到网络爬虫和数据提取方面程序员们的青睐。本文将简要介绍如何使用Python编写程序抓取HTMLtable数据。 一、http请求 首先需要使用Python的requests库进行http请求,获取到网站的html代码。我们可以使用get请求获取到网站的html代码,如下所示: ```python import requests url = 'http://www.example.com' response = requests.get(url) html = response.text ``` 如果需要传递参数,我们可以使用params参数: ```python params = {'search': 'iphone'} response = requests.get(url, params=params) ``` 二、解析html 获取html代码后,我们需要使用Python的解析库将其解析为可操作的数据结构。Python常见的解析库有:BeautifulSoup、lxml等。本文将使用BeautifulSoup解析库,需要使用以下命令进行安装: ```python pip install beautifulsoup4 ``` 小技巧:在解析html代码时,我们可以使用lxml库进行解析,速度比BeautifulSoup更快。但是在实际应用,最好同时安装两个库,进行快速切换。 使用BeautifulSoup进行解析: ```python from bs4 import BeautifulSoup soup = BeautifulSoup(html, 'html.parser') ``` 三、查找和拆分table数据 获取到解析后的数据后,可以使用find_all进行table标签的查找,如下所示: ```python table = soup.find_all('table') ``` 获取table数据后,我们可以将其拆分为行数据和列数据,如下所示: ```python rows = table[0].find_all('tr') for row in rows: cols = row.find_all('td') for col in cols: data = col.contents[0] if col.contents else '' ``` 其,cols是每行的列,可以使用该列的contents属性获取每个单元格的具体数据。需要注意的是,contents属性返回一个列表,因此需要进行判断,取得其的第0个元素。最后,我们可将所有的数据存放到列表,方便后续的数据处理。 综上所述,使用Python抓取HTMLtable数据需要完成如下三个步骤:建立http请求,解析HTML代码,查找和拆分table数据。如果能够熟练掌握这些步骤,相信可以快速地实现对HTMLtable数据抓取

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值