日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

Python获取外网ip

發布時間:2023/12/20 python 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Python获取外网ip 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

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.textip = 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.textip = txt[txt.find("[") + 1: txt.find("]")]print('ip:' + ip)return ipdef get_real_url(url=r'http://www.ip138.com/'):r = requests.get(url)txt = r.textsoup = BeautifulSoup(txt,"html.parser").iframereturn soup["src"]if __name__ == '__main__':get_out_ip(get_real_url())

這里用到了BeautifulSoup這個庫,從html源碼中找出對應的標簽與屬性值。

最后,上一張GoogleChrome瀏覽器顯示的源碼樣式。

總結

以上是生活随笔為你收集整理的Python获取外网ip的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。