-
大小: 1KB文件類型: .zip金幣: 2下載: 0 次發(fā)布日期: 2021-06-24
- 語言: 其他
- 標簽: 網(wǎng)絡(luò)爬蟲??網(wǎng)站鏈接??
資源簡介
本程序?qū)崿F(xiàn)了網(wǎng)絡(luò)爬蟲中爬取網(wǎng)頁鏈接的功能

代碼片段和文件信息
#include
#include
#include?“deelx.h“
#pragma?comment(lib?“WS2_32.lib“)
using?namespace?std;
void?main()
{
int?err=0;
char?sendBuf[200]={0};
char?hostName[200]={0};
char?host[200]={0}?path[200]={0};?
char?*pHost=NULL;
printf(“請輸入網(wǎng)址(例如:www.baidu.com)\n“);
cin>>hostName;
for?(pHost?=?hostName;?*pHost?!=?‘/‘?&&?*pHost?!=?‘\0‘;?++pHost);
if?(?(int)(pHost?-?hostName)?==?strlen(hostName)?)?//獲得相對地址
strcpy(path?“/“);?
else?
strcpy(path?pHost);?
*pHost?=?‘\0‘;?
strcpy(host?hostName);//獲得主機地址
/*
將要發(fā)送的HTTP報文
*/
sprintf(sendBuf“GET?“);
strcat(sendBufpath);
strcat(sendBuf“?HTTP/1.1\r\n“);
strcat(sendBuf“HOST:?“);
strcat(sendBufhost);
strcat(sendBuf“\r\nConnection:?Close\r\n\r\n“);
/*?
? windows下使用socket必須用WSAStartup初始化,否則不能調(diào)用?
*/?
WORD?w?=?MAKEWORD(20);;
WSADATA?data;
err?=?WSAStartup(w?&data);
if(err?!=?0)
{
cout<<“找不到可用的winsock.dll“< return;
}
SOCKET?client=socket(AF_INET?SOCK_STREAM?0);//建立socket套接字
if(client==INVALID_SOCKET)
{
cout<<“新建Socket失敗!“< return?;
}
/*
將主機域名轉(zhuǎn)化為IP地址
*/
struct?hostent?*lhost;
lhost?=?gethostbyname(host);
char?*ip?=?(char?*)inet_ntoa(*(struct?in_addr?*)(lhost->h_addr));
printf(“%s“ip);??//輸出ip地址
sockaddr_in?addr;
addr.sin_family?=?AF_INET;
addr.sin_port?=?htons(80);
addr.sin_addr.S_un.S_addr?=?inet_addr(ip);
if((connect(client(struct?sockaddr*)&addrsizeof(struct?sockaddr)))?==SOCKET_ERROR)//建立連接
{
cout<<“連接失敗,請重試!“< return;
}
send?(client??sendBuf??strlen(sendBuf)??0);//發(fā)送HTTP消息
static?CRegexpT??regexp(“\“[hH][tT]{2}[pP]\\:/{2}.*?(\“)“);//正則表達式
char?recvBuf[1024]={0};
char?*pRcv?=?recvBuf;
memset(recvBuf0x00sizeof(recvBuf));
int?recvresult?=?recv(client?recvBuf?1024?0);
while(recvresult>0)
{
MatchResult?Mr=regexp.Match(recvBuf);//從接收到的網(wǎng)頁源碼里提取出網(wǎng)站的鏈接
while(Mr.IsMatched())
{
char?resu[200]?=?“?“;
for?(int?i=0;?i resu[i]?=?recvBuf[Mr.GetStart()+i];
cout< Mr?=?regexp.Match(recvBuf?Mr.GetEnd());
}
memset(recvBuf0x00sizeof(recvBuf));
recvresult?=?recv(client?recvBuf?1024?0);
}
closesocket(client);?
WSACleanup();?
}
?屬性????????????大小?????日期????時間???名稱
-----------?---------??----------?-----??----
?????文件????????2456??2012-11-18?21:55??spider1.cpp
評論
共有 條評論