程序运行截图如下:
原理(原理和爬虫一样):
1.伪造HTTP数据封包头
2.处理爬下来的网站
关键代码如下:
inquireip.h
#ifndef INQUIREIP_H
#define INQUIREIP_H
#include <QObject>
#include <QTcpSocket>
class InquireIp : public QObject
{
Q_OBJECT
public:
explicit InquireIp(QObject *parent = 0);
void startConnect(const QString host,quint16 port);
void setIp(const QString ip);
public slots:
void onConnected();
void onReadyRead();
signals:
void sendIpLocation(QString msg);
protected:
void disposeHTTPContent(QString msg);
private:
QTcpSocket *m_socket;
QString m_ip;
QString m_httpContent;
};
#endif // INQUIREIP_H
inquireip.cpp
#include "inquireip.h"
#include <QDebug>
#include <QTextCodec>
#include <QByteArray>
InquireIp::InquireIp(QObject *parent) :
QObject(parent),m_socket(0),m_ip("")
{
m_ip="127.0.0.1";
}
void InquireIp::startConnect(const QString host, quint16 port)
{
m_socket=new QTcpSocket(this);
connect(m_socket,SIGNAL(connected()),this,SLOT(onConnected()));
connect(m_socket,SIGNAL(readyRead()),this,SLOT(onReadyRead()));
m_socket->connectToHost(host,port);
}
void InquireIp::setIp(const QString ip)
{
m_ip=ip;
}
void InquireIp::onConnected(){
QString msg=QString("GET /ips138.asp?ip=%1&action=2 HTTP/1.1\r\n"
"Host: www.ip138.com\r\n"
"User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:49.0) Gecko/20100101 Firefox/49.0\r\n"
"Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n"
"Accept-Language: zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3\r\n"
"Accept-Encoding: gzip, deflate\r\n"
"Referer: http://www.ip138.com/\r\n"
"Cookie: pgv_pvi=1815538688; pgv_si=s3422986240; ASPSESSIONIDCASTDCQB=CNPDBLMDPKKBEFLKKAMALGIK; ASPSESSIONIDQACDQCBR=DOAMDOGDCEGHLCPBBOIHKHFI\r\n"
"Connection: keep-alive\r\n"
"Upgrade-Insecure-Requests: 1\r\n\r\n").arg(m_ip);
m_socket->write(msg.toLatin1());
}
void InquireIp::onReadyRead()
{
QTextCodec *codec = QTextCodec::codecForName("gb2312");
QString qstr = codec->toUnicode(m_socket->readAll());
int q1=qstr.indexOf("<li>");
int q2=qstr.indexOf("</li>");
QString str=qstr.mid(q1+9,q2-q1);
QStringList strList=str.split(" ");
if(strList[0]=="")
return;
emit sendIpLocation(strList[0]);
}
void InquireIp::disposeHTTPContent(QString msg)
{
}