上一期我们学习了如何使用代理,很多小伙伴可能已经学会了,但是,有可能还不太放心,“我的ip地址真的已经变了吗?”,本期呢,就来写一个简单的爬虫,实现获取本机当前的ip地址
import requests
url = "http://httpbin.org/get"
p = input("请输入你的代理地址:")
headers = {"user-agent": "lsp"}
proxies = {
"http": "http://{}".format(p),
"https": "https://{}".format(p)
}
r1 = requests.get(url, headers=headers)
r2 = requests.get(url, headers=headers, proxies=proxies)
print("没有使用代理的ip地址为:", r1.json()["origin"])
print("使用代理的ip地址为:", r2.json()["origin"])
注:关于r.json()方法,我们在2-2期中已经有介绍过了,本期中也是第一次拿出来使用
如果你觉得只看ip地址不是很直观,我们也可以对其稍加修改,让其可以查询到本机ip地址的所在地
import requests
url = "https://2021.ip138.com/"
p = input("请输入你的代理地址:")
headers = {"user-agent": "lsp"}
proxies = {
"http": "http://{}".format(p),
"https": "https://{}".format(p)
}
r1 = requests.get(url, headers=headers)
r2 = requests.get(url, headers=headers, proxies=proxies)
print("没有使用代理的ip归属地为:", r1.text.split("来自:")[1].split("\n</p>")[0])
print("使用代理的ip归属地为:", r2.text.split("来自:")[1].split("\n</p>")[0])
注:如果运行该代码出现,"check_hostname requires server_hostname"的报错提示,运行以下指令即可
pip3 install urllib3==1.25.8
如果没有遇到该错误,可忽略此提示