[英]Python reads data from webpages
我有一堆IP地址的列表。 我想知道是否可以使用python通过从此网站( http://www.whatip.com/ip-lookup )提取信息来确定IP地址的国家/地区名称。 请查看下面的屏幕截图。 例如:IPlist = [“ 100.43.90.10”,“ 125.7.8.9.9”]
这是我的代码:我知道我可以通过将实际URL与后缀(=我的IP地址)串联来更改搜索URL。 我想得到“美国”
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>")
我检查了源代码中只有一个“国家”。 我了解我需要找到“国家/地区”的索引,然后打印出“美国”,但是我被卡住了。 有人告诉我该怎么做吗? 非常感谢!!
您可以使用此网站: http : //whatismyipaddress.com/ip/
您所需要做的就是编写一个Python脚本。 Python脚本将使用urllib3
库。 该库用于创建与Web的连接,设置IP地址数组并遍历它们,每次将IP地址附加到上述给定站点上。 使用urllib
创建一个http请求,一旦收到响应,就可以使用response的.data
属性获取响应数据。 收到响应数据后,使用简单的正则表达式查找国家/地区字段名称,然后仅获取国家/地区名称。
只需阅读urllib
文档,这很小! 完成了!
ps我一个月前做了类似的事情!
我建议使用可用于IP地理位置的许多REST API之一。
这不需要您安装任何新模块或执行任何网页抓取。 该请求返回一个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}
我发现使用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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.