您的位置:首页 > 编程语言 > Python开发

Python获取外网ip

2017-05-16 22:24 435 查看

Python获取外网ip

获取外网ip而不是局域网ip。网上有些教程但是不能用。因为有些地址已经过期用不了了。

此处介绍一种用ip138来查本机外网ip的方法。

直接上代码。

源码

import requests

# 获取外网IP
def get_out_ip():
url = r'http://1212.ip138.com/ic.asp'
r = requests.get(url)
txt = r.text
ip = txt[txt.find("[") + 1: txt.find("]")]
print('ip:' + ip)
return ip


至于这个链接http://1212.ip138.com/ic.asp是怎么来的。从浏览器看下源码,很多是无法直接找出自己的ip地址的字符串的,虽然实际界面上显示了自己的外网ip地址。

从html源码把对面显示真实ip地址的部分挑了出来如下

<div class="module mod-ip">
<h3>www.ip138.com IP查询(搜索IP地址的地理位置)</h3>
<iframe src="http://1212.ip138.com/ic.asp" rel="nofollow" frameborder="0" scrolling="no"></iframe>
<p>
<a class="blue" href="/kuandai/ruzhu.htm" target="_blank">宽带安装师傅申请入驻</a>
<span>|</span>
<a href="/idc/" target="_blank">idc公司大全</a>
<span>|</span>
<a class="red" href="http://user.ip138.com/ip/" target="_blank">ip查询接口</a>
</p>
<p>
在下面输入框中输入您要查询的IP地址或者域名,点击查询按钮即可查询该IP所属的区域。
</p>
<form method="get" action="ips138.asp" target="_blank" name="ipform">
<p>
<label for="ip">IP地址或者域名:</label>
<input class="input large-input" id="ip" type="text" name="ip" size="16"/>
<input type="hidden" name="action" value="2"/>
<input class="btn" type="submit" value="查询"/>
</p>
</form>
</div>


用GoogleChrome浏览器可以定位到源码对面的页面标签。是< iframe >模块。那么真实地址其实就是由这个地址返回的。

那么直接输入这个地址就可以看到返回了自己的真实外网ip地址和区域信息。

如果这个实际的请求网址经常换怎么办

可以再转一倒手,先把www.ip138.com的源码拿到,然后解析出< iframe >中的链接地址。

然后请求,最终获取到自己的外网ip地址。

上一版获取真实网址然后获取外网ip的代码。

import requests
from bs4 import BeautifulSoup

# 获取外网IP
def get_out_ip(url):
r = requests.get(url)
txt = r.text
ip = txt[txt.find("[") + 1: txt.find("]")]
print('ip:' + ip)
return ip

def get_real_url(url=r'http://www.ip138.com/'):
r = requests.get(url)
txt = r.text
soup = BeautifulSoup(txt,"html.parser").iframe
return soup["src"]

if __name__ == '__main__':
get_out_ip(get_real_url())


这里用到了BeautifulSoup这个库,从html源码中找出对应的标签与属性值。

最后,上一张GoogleChrome浏览器显示的源码样式。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息