如何用Python编写一个简单的手机号码归属地查询程序
发布时间:2023-12-04 14:14:05
要编写一个简单的手机号码归属地查询程序,我们需要以下步骤:
1. 导入所需的库:我们将使用requests库发送HTTP请求和BeautifulSoup库解析HTML响应。请确保这两个库已经安装在您的Python环境中。
import requests from bs4 import BeautifulSoup
2. 定义一个函数来查询手机号码的归属地。在这个函数中,我们将构造一个URL,发送HTTP请求,并解析响应以获取归属地信息。
def query_location(phone_number):
# 构造URL
url = 'https://www.ip138.com/mobile.asp?mobile=' + phone_number
# 发送HTTP请求
response = requests.get(url)
# 解析HTML响应
soup = BeautifulSoup(response.content, 'html.parser')
# 获取归属地信息
location = soup.select('#result > div:nth-child(2)')[0].text.strip()
return location
3. 在主程序中,可以通过调用该函数来查询任意手机号码的归属地。例如:
phone_number = input("请输入手机号码:")
location = query_location(phone_number)
print("手机号码 %s 的归属地是:%s" % (phone_number, location))
完整的代码如下:
import requests
from bs4 import BeautifulSoup
def query_location(phone_number):
url = 'https://www.ip138.com/mobile.asp?mobile=' + phone_number
response = requests.get(url)
soup = BeautifulSoup(response.content, 'html.parser')
location = soup.select('#result > div:nth-child(2)')[0].text.strip()
return location
phone_number = input("请输入手机号码:")
location = query_location(phone_number)
print("手机号码 %s 的归属地是:%s" % (phone_number, location))
使用该程序时,您可以输入一个手机号码,然后程序将会查询该手机号码的归属地,并打印出结果。请注意,此程序只适用于中国手机号码。
示例输出:
请输入手机号码:13800138000 手机号码 13800138000 的归属地是:中国移动
在上面的例子中,我们查询了手机号码13800138000的归属地。查询结果显示该号码属于中国移动。
