用C编程从网页数据库中提取内容 (c 编程提取网页数据库中内容)

用C语言编程从网页数据库中提取内容

在大数据时代,数据是一种非常宝贵的资源。许多网站都提供API接口,供开发人员使用,但对于一些没有API接口的网站,我们需要使用其他方法来提取数据。本文将介绍如何使用C语言编程从网页数据库中提取内容。

1. 网页抓取

我们需要进行网页抓取。在C语言中,我们可以使用socket和HTTP协议来实现网页抓取。以下是一个简单的示例,使用socket连接目标网站,并获取网页内容:

“`c

#include

#include

#include // 在 Windows 平台需要添加该头文件

#pragma comment(lib,”ws2_32.lib”) // Windows 平台需要添加这行代码

int mn()

{

WSADATA wsaData;

WSAStartup(MAKEWORD(2,1), &wsaData); // 初始化WinSock库

SOCKET s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); // 创建套接字

SOCKADDR_IN serverAddr;

serverAddr.sin_family = AF_INET;

serverAddr.sin_port = htons(80);

serverAddr.sin_addr.s_addr = inet_addr(“192.168.0.1”);

connect(s, (SOCKADDR*)&serverAddr, sizeof(serverAddr)); // 连接到目标服务器

char buf[4096];

char request[1024];

sprintf_s(request, “GET / HTTP/1.1\r\nHost: 192.168.0.1\r\nConnection: close\r\n\r\n”); // 发送 GET 请求

send(s, request, strlen(request), 0); // 发送请求

int nBytes;

while ((nBytes = recv(s, buf, sizeof(buf), 0)) > 0) // 接收响应

{

buf[nBytes] = 0; // 添加字符串结束符

printf(“%s”, buf); // 输出响应

}

closesocket(s); // 关闭套接字

WSACleanup(); // 释放 WinSock 库资源

return 0;

}

“`

2. 解析HTML

接下来,我们需要解析HTML代码,找到我们需要的数据。我们可以使用libxml2库来解析HTML,以下是一个简单的示例:

“`c

#include

#include

void startElement(void *ctx, const xmlChar *name, const xmlChar **attrs)

{

printf(“start element: %s\n”, name);

}

void endElement(void *ctx, const xmlChar *name)

{

printf(“end element: %s\n”, name);

}

int mn()

{

htmlSAXHandler saxHandler = {0};

saxHandler.startElement = startElement;

saxHandler.endElement = endElement;

xmlSAXUserParseMemory(&saxHandler, NULL, “

hello world

“, strlen(“

hello world

“));

return 0;

}

“`

上述代码解析了一个简单的HTML代码,并打印了标签的起始和结束。

3. 解析ON

除了解析HTML,我们还需要解析ON格式的数据。对于ON格式的数据,我们可以使用cON库来解析。以下是一个示例:

“`c

#include

#include

#include “cON.h”

int mn()

{

char jsonStr[] = “{\”name\”:\”John\”,\”age\”:30,\”city\”:\”New York\”}”;

cON *json = cON_Parse(jsonStr);

if (json == NULL)

{

printf(“parse error\n”);

return -1;

}

cON *name = cON_GetObjectItem(json, “name”);

if (name == NULL)

{

printf(“name not found\n”);

cON_Delete(json);

return -1;

}

printf(“name: %s\n”, name->valuestring);

cON *age = cON_GetObjectItem(json, “age”);

if (age == NULL)

{

printf(“age not found\n”);

cON_Delete(json);

return -1;

}

printf(“age: %d\n”, age->valueint);

cON *city = cON_GetObjectItem(json, “city”);

if (city == NULL)

{

printf(“city not found\n”);

cON_Delete(json);

return -1;

}

printf(“city: %s\n”, city->valuestring);

cON_Delete(json);

return 0;

}

“`

上述代码解析了一个简单的ON,并输出了其中的每个字段。

4. 数据库操作

我们需要将抓取到的数据存储到数据库中。对于SQLite数据库,我们可以使用SQLite3库来实现。以下是一个简单的示例:

“`c

#include

#include

#include

int mn()

{

sqlite3 *db;

int rc = sqlite3_open(“test.db”, &db);

if (rc != SQLITE_OK)

{

printf(“open database error\n”);

return -1;

}

char *sql = “CREATE TABLE IF NOT EXISTS person (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, age INTEGER NOT NULL);”;

rc = sqlite3_exec(db, sql, NULL, NULL, NULL);

if (rc != SQLITE_OK)

{

printf(“execute error\n”);

return -1;

}

sql = “INSERT INTO person (name, age) VALUES (‘John’, 30);”;

rc = sqlite3_exec(db, sql, NULL, NULL, NULL);

if (rc != SQLITE_OK)

{

printf(“execute error\n”);

return -1;

}

sqlite3_close(db);

return 0;

}

“`

上述代码创建了一个名为test.db的SQLite数据库,并创建了一个person表。然后插入了一个John的记录。

相关问题拓展阅读:

高分求c#网页数据保存:保存网页内容到数据库中 代码

///

/// 读取指定URL地址,存到指定文件中

///

public bool GetSource(Encoding PageEncoding)

{

bool isGet = false;

try

{

WebRequest request = WebRequest.Create(this.url);

//迅哗使用代理服务器的处理

if (this.proxyState == 1)

{

//亩陆行默认读取80端口的数据

if (this.proxyPort == null)

this.ProxyPort = “80”;

WebProxy myProxy = new WebProxy();

myProxy = (WebProxy)request.Proxy;

myProxy.Address = new Uri(this.ProxyAddress + “:” + this.ProxyPort);

myProxy.Credentials = new NetworkCredential(this.proxyAccount, this.proxyPassword, this.ProxyDomain);

request.Proxy = myProxy;

}

//请求服务

WebResponse response = request.GetResponse();

//返回信息

Stream resStream = response.GetResponseStream();

StreamReader sr = new StreamReader(resStream, PageEncoding);

string tempCode = sr.ReadToEnd();

resStream.Close();

sr.Close();

this.outString = tempCode;

//如悉盯果输出文件路径为空,便将得到的内容赋给OutString属性

if (this.outFilePath != null)

{

FileInfo fi = new FileInfo(this.outFilePath);

//如果存在文件则先干掉

if (fi.Exists)

fi.Delete();

StreamWriter sw = new StreamWriter(this.outFilePath, true, Encoding.Default);

sw.Write(tempCode);

sw.Flush();

sw.Close();

}

return !isGet;

}

catch

{

this.noteMessage = “出错了,请检查网络是否连通;”;

return isGet;

}

}

以上是把网页的内容取了回来,接下来,你把那个OutString存到你的数据库就行了.

这个保存数据到数据坦塌磨库这里那你会不会了,会的话就请看下面,不衫销会的话那就去学下这个ADO.NET这个最基本的知识点.

protected string getHtml(string url)

{

HttpWebRequest webRequest = null;

HttpWebResponse webResponse = null;

StreamReader streamReader = null;

string content=string.Empty;

try

{

webRequest = (HttpWebRequest)WebRequest.Create(url);

webRequest.Method = “GET”;

webResponse = (HttpWebResponse)webRequest.GetResponse();

Stream stream = webResponse.GetResponseStream();

streamReader = new StreamReader(stream, System.Text.Encoding.GetEncoding(“GB2312”));

content = streamReader.ReadToEnd();

}

catch

{

throw;

}

finally

{

streamReader.Close();

webResponse.Close();

}

return content;

}

protected void Button1_Click(object sender, EventArgs e)

{

string url = this.TextBox1.Text.Trim();

Response.Write(getHtml(url));

}

记让斗得导入命名空间System.Net;System.IO;

这样通过按钮操作就可以读取某个网址的的HTML代码。返回的是一个string字符串类型!

然后就可以保存到数据库了!

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;

//增加以下命名空蔽昌间

using System.Net;

using System.IO;

using System.Data.OleDb;

namespace PageCodeDownloader

{

public partial class MainForm : Form

{

private string dbConnectionString = string.Empty;

private OleDbConnection dbConnection = null;

private OleDbCommand dbCommand = null;

public MainForm()

{

InitializeComponent();

//界面上增加一个TextBox,修改Name属性为:txtPageUrl

//界面上增加一个Button,修改Name属性为btnDownload

//新建一数据库名为db.mdb

//增加一张大消表:download

//表字段: id 自动编号

//url 文本(255)

//宏仿扒pagecode 备注

this.dbConnectionString = @”Provider=Microsoft.Jet.OLEDB.4.0;Data Source=.\db.mdb”;

this.dbConnection = new OleDbConnection(this.dbConnectionString);

}

private void btnDownload_Click(object sender, EventArgs e)

{

if (txtPageUrl.Text != “”)

{

try

{

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(txtPageUrl.Text);

Stream responseStream = request.GetResponse().GetResponseStream();

StreamReader sr = new StreamReader(responseStream,Encoding.Default);

string strPageCode = sr.ReadToEnd();

sr.Close();

string sql = string.Format(“Insert into (,) values(‘{0}’,@PageCode)”,txtPageUrl.Text);

this.dbCommand = new OleDbCommand(sql, this.dbConnection);

this.dbCommand.CommandType = CommandType.Text;

if (this.dbCommand.Connection.State == ConnectionState.Closed)

{

this.dbCommand.Connection.Open();

}

this.dbCommand.Parameters.Add(new OleDbParameter(“@PageCode”,strPageCode));

int EffectRowCount = this.dbCommand.ExecuteNonQuery();

if (EffectRowCount > 0)

{

MessageBox.Show(“保存成功”);

}

else

{

MessageBox.Show(“保存失败”);

}

}

catch (Exception err)

{

MessageBox.Show(err.Message);

}

}

else

{

MessageBox.Show(“请输入要获取代码的Url”);

}

}

}

}

private void btnSubmit_Click ( object sender, EventArgs e )

{

string strURL = this.txtURl.Text.Trim ( );

Regex regex = new Regex ( @”http(s)?://(+\.)++(/*)?”, RegexOptions.IgnoreCase );

Match match = regex.Match ( strURL );

if ( match.Success )

{

WebClient client = new WebClient ();

try

{

string strResult = client.DownloadString ( strURL );

this.SaveResult ( strResult );

}

catch ( Exception ex )

{

MessageBox.Show ( ex.Message );

}

finally

{

client.Dispose ( );

}

}

else

{

MessageBox.Show ( strURL + “不是一个有效的网址, 请重新输入!”, “信息提示”, MessageBoxButtons.OK );

this.txtURl.Select ( );

}

}

private void SaveResult ( string result )

{

OleDbConnection connection = new OleDbConnection ( “Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Data\\Database.mdb” );

try

{

connection.Open ( );

OleDbCommand command = connection.CreateCommand ( );

command.CommandType = CommandType.Text;

command.CommandText = “INSERT INTO () VALUES(@Content)”;

OleDbParameter param = new OleDbParameter();

param.ParameterName = “@Content”;

param.Value = result;

command.Parameters.Add(param);

int RowCount = command.ExecuteNonQuery ( );

if ( RowCount > 0 )

{

MessageBox.Show ( “网页抓取并保存成功.” );

}

else

{

MessageBox.Show ( “网页成功,但是保存失败.” );

}

}

catch ( OleDbException ex )

{

MessageBox.Show ( ex.Message );

}

finally

{

connection.Close ( );

}

}

代码没空写,方法可以提供:

1.界面最简单,PASS

2.连接数据库语句,连接SQL或ACCESS需要确定用何种方式,直接连还是ODBC。

3。设计数据库结构,如何存储你的网页,其实是网页信裤睁息摘姿锋取了。

4.连接数据库过程:打开数据库,建立连接,传递查询语句,接收返回值,由返回值判断结迹纯晌果返回给界面。

要想学习,别再要代码,切记。

C++用libcurl库GET网页(比如baidu.com)并将获取到的网页内容保存到本地文件夹中

#include

#include “curl/curl.h”

#pragma comment(lib, “ws2_32.lib”)

#pragma comment ( lib, “libcurl.lib” )

#pragma comment ( lib, “ws2_32.lib” )

#pragma comment ( lib, “winmm.lib” )

#pragma comment ( lib, “wldap32.lib” )

//这是libcurl接收数据的回调函数,相当于recv的死循环

//其中stream可以自定义数据类型,这里我传入的是文件保存路径

static size_t write_callback( void *ptr, size_t size, size_t nmemb, void *stream )

{

int len = size * nmemb;

int written = len;

FILE *fp = NULL;

if ( access( (char*)stream, 0 ) == -1 )

{

fp = fopen( (char*) stream, “wb” );

}

else

{

fp = fopen( (char*) stream, “ab” );

}

if (fp)

{

fwrite( ptr, size, nmemb, fp );

}

return written;

}

int GetUrl( const char *url, char *savepath )

{

CURL *curl;

CURLcode res;

struct curl_slist *chunk = NULL;

curl = curl_easy_init();

if ( curl ) {

curl_easy_setopt( curl, CURLOPT_VERBOSE, 0L );

curl_easy_setopt( curl, CURLOPT_URL, url );

//指定回调函数

curl_easy_setopt( curl, CURLOPT_WRITEFUNCTION, write_callback);

//这个变量可作为接收或传递数据的作用

curl_easy_setopt( curl, CURLOPT_WRITEDATA, savepath );

res = curl_easy_perform( curl );

if (res == CURLE_OK)

{

return 1;

}

return 0;

}

}

int main( void )

{

if ( GetUrl( “t.sin.cn”, “c:/1.txt” ) )

{

printf( “OK” );

}

return 0;

}

如何用一个C#页面查询数据库内数据并在页面中显示查询的内容

因为无法确定你使用的具体技术,所以没法告诉你具体操作,但是渣族大致用到的技术如下:

html(写网页)

数据库(查询数据)

一门服务端语言(含配连接html和数据库)

服务器部谈梁指署(项目发布)

域名

c 编程提取网页数据库中内容的介绍就聊到这里吧,感谢你花时间阅读本站内容,更多关于c 编程提取网页数据库中内容,用C编程从网页数据库中提取内容,高分求c#网页数据保存:保存网页内容到数据库中 代码,C++用libcurl库GET网页(比如baidu.com)并将获取到的网页内容保存到本地文件夹中,如何用一个C#页面查询数据库内数据并在页面中显示查询的内容的信息别忘了在本站进行查找喔。


数据运维技术 » 用C编程从网页数据库中提取内容 (c 编程提取网页数据库中内容)