python爬虫手机号码归属地查询
时间: 2024-01-08 13:03:38 浏览: 70
以下是一个使用Python爬虫查询手机号码归属地的示例代码:
```python
import requests
def get_mobile_location(mobile):
url = 'https://www.ip138.com/mobile.asp?mobile=' + mobile
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'
}
response = requests.get(url, headers=headers)
response.encoding = 'gb2312'
html = response.text
location_start = html.find('<td class="tdc2">') + len('<td class="tdc2">')
location_end = html.find('</td>', location_start)
location = html[location_start:location_end]
return location
mobile = '13812345678'
location = get_mobile_location(mobile)
print('手机号码', mobile, '归属地为', location)
```
该代码使用requests库发送HTTP请求,通过解析返回的HTML页面获取手机号码的归属地信息。具体步骤如下:
1. 构造查询URL,将手机号码作为参数拼接在URL中。
2. 添加请求头,模拟浏览器发送请求。
3. 发送GET请求,获取响应内容。
4. 解析HTML页面,提取归属地信息。
5. 返回归属地信息。
请注意,该示例代码仅适用于特定的网站,如果要查询其他网站的手机号码归属地,需要根据网站的HTML结构进行相应的修改。