全国邮编的网址:http://www.ip138.com/post/
我们这次是爬取 每一个省里面的所有邮编信息
这里要进行二次爬取,才能完全获取完数据.
import requests,re
#代理ip
proxy={
"HTTP": "113.3.152.88:8118",
"HTTPS": "219.234.5.128:3128",
}
#伪装头信息
headers={
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36',
}
#根据正常跳转获取网址 分析网址,再进行拼接
# url="http://alexa.ip138.com/post/search.asp?page=503®ionid=2"
url="http://www.ip138.com/post/"
response=requests.get(url,headers=headers,proxies=proxy)
#网址编码为gbk 所以解码为gbk不再是utf-8
html=response.content.decode('gb2312')
#提取每个省的连接id码 用于第二次拼接url 请求
rec=re.compile(r'<a href="/(.*?)/" target="_blank">(.*?)</a>')
ret=rec.findall(html)
for i in ret:
print("地区:"+i[-1]+" "+"编号:"+i[0])
print()
msg=input("请输入要查询地区的编号:")
#拼接url
url_yz="http://www.ip138.com/%s/"%msg
response=requests.get(url_yz,headers=headers,proxies=proxy)
html_place=response.content.decode('gbk')
# print(html_place)
# \u4e00-\u9fa5
# 正则中这个代表匹配所有中文字符
rec_place=re.compile(r'<td>([\u4e00-\u9fa5]*?)</td><td><a href="/.*?/">(.*?)</a></td><td><a href="/.*?/">(.*?)</a></td>')
ret_place=rec_place.findall(html_place)
for i in ret_place:
print("市县区名:"+i[0]+" 邮政编码:"+i[1]+" 长途区号:"+i[-1])
这样就可以完全把所有省市邮编都爬取完毕了