我有一堆IP地址列表。我想知道是否可以通过从这个网站(http://www.whatip.com/ip-lookup)中提取信息来使用python来确定IP地址的国家名称。请参阅下面的屏幕截图。 例如:IPlist = [" 100.43.90.10"," 125.7.8.9.9"]
这是我的代码:我知道我可以通过将实际网址与后缀(=我的IP地址)连接来更改搜索网址。我想得到#34;美国"
import urllib.request
with urllib.request.urlopen('http://www.whatip.com/ip/100.43.90.10') as response:
html = response.read()
print (html)
text = html.decode()
start = text.find("<td>Country:</td>")
我检查过只有一个&#34;国家&#34;在源代码中。我知道我需要找到&#34; Country&#34;的索引,然后打印出&#34;美国&#34;但我卡住了任何人都告诉我该怎么做?非常感谢!!
答案 0 :(得分:1)
您可以使用此网站:http://whatismyipaddress.com/ip/
您需要做的就是编写一个Python脚本。 Python脚本将使用 yAxis: [{
title: {
text: 'Total percent market share'
}
},
{
title: {
text: 'cost'
},
opposite: true
}],
库。此库用于创建与Web的连接,设置IP地址数组并循环访问它们,每次将IP地址附加到上面给定的站点。使用urllib3
创建http请求,收到响应后,您可以使用响应的urllib
属性来获取响应数据。收到响应数据后,使用简单的正则表达式查找国家/地区字段名称,然后只需获取国家/地区名称。
只需查看.data
文档即可!你完成了!
P.S。一个月前我做了类似的事情!
答案 1 :(得分:1)
我建议使用可用于IP地理位置的many REST APIs之一。
这不需要您安装任何新模块或执行任何网页抓取。请求返回一个json对象,您可以使用内置模块进行解析并立即创建python字典。
我与nekudo进行了快速合作,看起来效果很好:
import json
from http import client
# Connect to the client
conn = client.HTTPConnection("geoip.nekudo.com")
# Make the request and extract the data
conn.request("GET","/api/172.217.3.110/full")
json_data = conn.getresponse().read().decode()
# Convert the JSON to a Python object
data = json.loads(json_data)
data
现在是一个Python字典,包含您需要的所有信息
>>> data['registered_country']['names']['en']
'United States'
>>> data['location']
{'latitude': 37.4192, 'metro_code': 807, 'time_zone': 'America/Los_Angeles', 'longitude': -122.0574}
答案 2 :(得分:1)
我发现使用API几乎总是比屏幕抓取网页更容易。以下是使用ip-api.com的一种解决方案:
import requests
import json
IPlist = ["100.43.90.10","125.7.8.9.9"]
request = json.dumps([{'query':ip, 'fields':'country'} for ip in IPlist])
response = requests.post('http://ip-api.com/batch', data=request).json()
print '\n'.join('{}: {}'.format(ip, data.get('country', 'Unknown'))
for ip, data in zip(IPlist, response))