(網絡爬蟲的構成及分類 網絡爬蟲又被稱為做網絡蜘蛛、網絡機器人,主要用於網絡資源的收集工作。在進行網絡輿情分析時,首要獲取輿情信息內容,這就需要用到網絡爬蟲(蜘蛛程序)這個工具,它是一個能自動提取網頁內容的程序,通過搜索引擎從互聯網上爬取網頁地址並抓取相應的網頁內容,是搜索引擎(Search Engine)的重要組成部分。 一個典型的網絡爬蟲主要組成部分如下: 1. URL 鏈接庫,主要用於存放爬取網頁鏈接。 2. 文檔內容模塊,主要用於存取從 Web 中下載的網頁內容。 3. 文檔解析模塊,用於解析下載文檔中的網頁內容,如解析 PDF,Word,HTML 等。 4. 存儲文檔的元數據以及內容的庫。 5. 規範化 URL 模塊,用於把 URL 轉成標準的格式。 6. URL 過濾器,主要用於過濾掉不需要的 URL。
代碼如下:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: main.cpp
* Author: yangchao
*
* Created on 2017年6月4日, 下午3:00
*/
#include <iostream>
#include <string>
#include <netdb.h>
#include <string.h>
#include <stdlib.h>
using namespace std;
void parseHostAndPagePath(const string url,string &hostUrl,string &pagePath){
hostUrl=url;
pagePath="/";
int pos=hostUrl.find("http://");
if(-1!=pos)
hostUrl=hostUrl.replace(pos,7,"");
pos=hostUrl.find("https://");
if(-1!=pos)
hostUrl=hostUrl.replace(pos,8,"");
pos=hostUrl.find("/");
if(-1!=pos)
{
pagePath=hostUrl.substr(pos);
hostUrl=hostUrl.substr(0,pos);
}
}
string getPageContent(const string url){
struct hostent *host;
string hostUrl,pagePath;
parseHostAndPagePath(url,hostUrl,pagePath);
if(0==(host=gethostbyname(hostUrl.c_str())))
{
cout<<"gethostbyname error\n"<<endl;
exit(1);
}
struct sockaddr_in pin;
int port=80;
bzero(&pin,sizeof(pin));
pin.sin_family=AF_INET;
pin.sin_port=htons(port);
pin.sin_addr.s_addr=((struct in_addr*)(host->h_addr))->s_addr;
int isock;
if((isock=socket(AF_INET,SOCK_STREAM,0))==-1)
{
cout<<"open socket error\n"<<endl;
exit(1);
}
string requestHeader;
requestHeader="GET "+pagePath+" HTTP/1.1\r\n";
requestHeader+="Host: "+hostUrl+"\r\n";
requestHeader+="Accept: */*\r\n";
requestHeader+="User-Agent: Mozilla/4.0(compatible)\r\n";
requestHeader+="connection:Keep-Alive\r\n";
requestHeader+="\r\n";
if(connect(isock,(const sockaddr*)&pin,sizeof(pin))==-1){
cout<<"connect error\n"<<endl;
exit(1);
}
if(send(isock,requestHeader.c_str(),requestHeader.size(),0)==-1){
cout<<"send error\n"<<endl;
exit(1);
}
struct timeval timeout={1,0};
setsockopt(isock,SOL_SOCKET,SO_RCVTIMEO,(char*)&timeout,sizeof(struct timeval));
char c;
bool flag=true;
while(recv(isock,&c,1,0)>0){
if('\r'==c){
continue;
}else if('\n'==c){
if(false==flag)
break;
flag=false;
}else{
flag=true;
}
}
int len,BUFFER_SIZE=512;
char buffer[BUFFER_SIZE];
string pageContent="";
while((len=recv(isock,buffer,BUFFER_SIZE-1,0))>0){
buffer[len]='\0';
pageContent+=buffer;
}
return pageContent;
}
int main(int argc, char** argv) {
cout<<getPageContent("http://www.hao123.com")<<endl;
return 0;
}