思路:把 IP 地址当关键词拼上百度的搜索链接,然后用正则匹配想要的信息。
代码:
import re
import requests
requests.packages.urllib3.disable_warnings()
def get_ipv4(ip):
"""
获取 IPv4
:param ip:
:return:
"""
# IP patterns
ipv4_re = r'(?:25[0-5]|2[0-4]\d|[0-1]?\d?\d)(?:\.(?:25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}'
# ipv6_re = r'\[[0-9a-f:\.]+\]' # (simple regex, validated later)
ipv4 = re.search(ipv4_re, ip)
if ipv4:
return ipv4.group()
return ip
def ip_location_baidu(ip):
"""
从 百度搜索 获取 IP 的 归属地
:param ip:
:return:
"""
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) \
Chrome/53.0.2785.104 Safari/537.36 Core/1.53.4549.400 QQBrowser/9.7.12900.400"
}
ipv4 = get_ipv4(ip)
url = r'https://www.baidu.com/s?wd=%s' % ipv4
result = requests.get(url=url, headers=headers, verify=False).text
re_compile = re.compile("IP地址: %s</span>(.*?)</td></tr></table>" % ipv4, re.S)
ip_location = re.findall(re_compile, result)
if ip_location:
ip_location = ip_location[0].replace("\t", "").replace("\n", "").replace(" ", "")
ip_location = ip_location.replace("省", "·").replace("市", "").replace("电信", "").replace("联通", "").replace(
"移动", "")
return ip_location
else:
return None
if __name__ == "__main__":
print(ip_location_baidu("106.11.153.104"))