python爬虫IP地址解析爬取(IP38.com)
上个月做了个离线IP解析,今天突发奇想用python写了个爬虫。通过IP38.com进行ip解析。说实话比离线解析准确多了。但要求就是要连接互联网。代码很暴力,建议优化。
import urllib.request,urllib.error
import re
def askurl(url):
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.75 Safari/537.36 Edg/100.0.1185.36"
} # 高数服务器是我们是什么信息
req = urllib.request.Request(url, headers=headers)
html = ""
try:
response = urllib.request.urlopen(req, timeout=10)
html = response.read().decode("gbk")
# print(html)
except urllib.error.URLError as e:
if hasattr(e, "code"):
print(e.code)
if hasattr(e, "reason"):
print(e.reason)
return html
if __name__ == '__main__':
ip="125.196.21.132"
url="https://www.ip138.com/iplookup.asp?ip="+ip+"&action=2"
html=askurl(url)
res=re.compile(r'var ip_result =.*')
ress=res.search(html)
resss=str(ress).split(":")
print(resss[1].split('"')[1])
代码很暴力,以实现功能为目的。大佬轻喷