马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 591821661 于 2021-4-27 21:48 编辑
遵循开源精神 把自己写的小模块分享到论坛 同时希望有大佬能够给出requests的代理实例~ # -*- coding: utf-8 -*-
"""
Created on Tue Apr 27 19:32:49 2021
@author: Sharpstar_kylin
"""
import urllib.request
import json
import sys
import requests
def urllib_useproxy(proxy=''):
if proxy:
proxy_support = urllib.request.ProxyHandler({
'http' : proxy,
'https' : proxy,
})
else:
proxy_support = urllib.request.ProxyHandler({
})
opener = urllib.request.build_opener(proxy_support)
opener.addheaders = [('User-Agent', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.85 Safari/537.36'),
]
urllib.request.install_opener(opener)
def urllib_get_ip(proxy):
# Get IP Address
try:
urllib_useproxy(proxy) # 正常
ip_api_url = 'http://ip-api.com/json/?fields=61439'
ip_result = urllib.request.urlopen(ip_api_url)
proxy_text = ip_result.read().decode('utf-8')
s_get_dict = json.loads(proxy_text)
print('urllib\'s response: %s' % ip_result.code)
print('----------------------IP Information Begin--------------------------')
for key in s_get_dict:
print('%s : %s' % (key, s_get_dict[key]))
print('----------------------IP Information End--------------------------\n')
except:
print('url_get error')
print(sys.exc_info()[0], sys.exc_info()[1])
def requests_get_ip(proxy):
# Get IP Address
try:
proxies = {
"http": proxy,
"https": proxy,
}
res = requests.get(ip_api_url, proxies=proxies)
proxy_text = res.content.decode('utf-8')
s_get_dict = json.loads(proxy_text)
print('Requests\'s response : %s' % res.status_code)
print('----------------------IP Information Begin--------------------------')
for key in s_get_dict:
print('%s : %s' % (key, s_get_dict[key]))
print('----------------------IP Information End--------------------------\n')
except:
print('url_get error')
print(sys.exc_info()[0], sys.exc_info()[1])
if __name__ == '__main__': # 如果运行该文件,而不是作为库函数导入 则运行下列代码
ip_api_url = 'http://ip-api.com/json/?fields=61439'
# proxy = '127.0.0.1:1080' #使用代理
proxy = '' #不使用代理
urllib_get_ip(proxy)
requests_get_ip(proxy)
|