#导入urllib.request模块
import urllib.request
#设置请求头
headers=("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.221 Safari/537.36 SE 2.X MetaSr 1.0")
#创建一个opener
opener=urllib.request.build_opener()
#将headers添加到opener中
opener.addheaders=[headers]
#将opener安装为全局
urllib.request.install_opener(opener)
#用urlopen打开网页
data=urllib.request.urlopen(url).read().decode('utf-8','ignore')
#定义代理ip
proxy_addr="122.241.72.191:808"
#设置代理
proxy=urllib.request.ProxyHandler({'http':proxy_addr})
#创建一个opener
opener=urllib.request.build_opener(proxy)
#将opener安装为全局
urllib.request.install_opener(opener)
#用urlopen打开网页
data=urllib.request.urlopen(url).read().decode('utf-8','ignore')
#定义代理ip
proxy_addr="122.241.72.191:808"
#创建一个请求
req=urllib.request.Request(url)
#添加headers
req.add_header("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko)
#设置代理
proxy=urllib.request.ProxyHandle("http":proxy_addr)
#创建一个opener
opener=urllib.request.build_opener(proxy,urllib.request.HTTPHandler)
#将opener安装为全局
urllib.request.install_opener(opener)
#用urlopen打开网页
data=urllib.request.urlopen(req).read().decode('utf-8','ignore')
# 爬取首页代理IP地址
# Python学习交流群:
from bs4 import BeautifulSoup
import requests
import random
# 获取首页IP列表
def get_ip_list(url, headers):
web_data = requests.get(url, headers=headers)
soup = BeautifulSoup(web_data.text, 'lxml')
ips = soup.find_all('tr')
ip_list = []
# 提取ip列表
# range()的用法:range(1,5) #代表从1到5(不包含5)
for i in range(1, len(ips)):
ip_info = ips[i]
tds = ip_info.find_all('td')
ip_list.append(tds[5].text.lower() + '://' + tds[1].text + ':' + tds[2].text)
return ip_list
# 随机获取一个ip
def get_random_ip(ip_list):
# 随机获取一个ip(从返回的ip列表里面)
proxy_ip = random.choice(ip_list)
return proxy_ip
# 测试
if __name__ == '__main__':
# 国内高匿代理IP
url = 'http://www.xicidaili.com/nn/'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36'
}
# 获取首页ip列表
ip_list = get_ip_list(url, headers=headers)
# 随机提取一个ip
ip = get_random_ip(ip_list)
print('代理ip地址:' + ip)