爬虫时,为了避免自己的IP被封,有时候需要设置反向代理,用其他的IP去爬。那么这里说的IP到底是电脑的什么IP呢?
首先看下localhost
、127.0.0.1
、192.168.x.x
。
这里使用flask开启一个服务,这样本机可以通过localhost
、127.0.0.1
、192.168.x.x
(我的是192.168.1.4
)等地址的5000端口(eg. 192.168.1.4:5000
)访问服务器,而同一局域网的其它设备也可以通过192.168.1.4:5000
访问我的服务器
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
return 'Hello World'
if __name__ == '__main__':
app.run(
host='0.0.0.0', # 接受任意 ip 地址的连接
port=5000
)
这里的localhost
一般默认指向127.0.0.1
,所以只需要看IP
127.0.0.1
是只能自己对自己使用的IP
192.168.x.x
则是局域网下任何设备都可以访问其他设备使用的IP(包括自己对自己)
然后,如果我访问在线网站,或者爬虫,使用的IP并不是上面那两个IP,而是我的运营商分配给我的外网IP(public ip),作为我使用的这个网络的一个身份标识,一般反爬虫封的IP,也就是这个IP了
那么如何获取呢?
- 对于不懂网络的人,可以直接在百度输入
ip
,就可以知道了
image.png
- 使用python(不限语言)向提供IP查询的地址执行请求,然后从返回的数据中提取出IP
python版本:
from urllib import request
import re
# 通过sohu公共ip库获取本机公网ip
def get():
sohu_ip_url = 'http://txt.go.sohu.com/ip/soip'
r = request.urlopen(sohu_ip_url)
text = r.read().decode()
result = re.findall(r'\d+.\d+.\d+.\d+', text)
if result:
return result[0]
else:
return None
nodejs版本:
const http = require('http')
function getIP(cb) {
const url = 'http://txt.go.sohu.com/ip/soip'
http.get(url, res => {
let data = ''
res.on('data', chunk => data += chunk)
res.on('end', () => {
let m = data.match(/\d+\.\d+\.\d+\.\d+/g)
if (m.length > 0) {
cb(m[0])
}
})
}).on('error', e => console.log(`error messsage: ${e.message}`))
}
- 使用语言对应的模块或者插件(github一堆)
参考链接:
网友评论