Python3.x:获取代理ip以及使用

Python3.x:获取代理ip以及使用

python爬虫浏览器伪装

#导入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

# python3
# 国内高匿代理IP网站:http://www.xicidaili.com/nn/
# 爬取首页代理IP地址

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)

常用的代理ip地址:

1,西刺免费代理IP:http://www.xicidaili.com/

2,国内高匿代理IP:http://www.xicidaili.com/nn/

3,66免费代理网:http://www.66ip.cn/

作者:整合侠
链接:http://www.cnblogs.com/lizm166/p/8191305.html
来源:博客园
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

原文地址:https://www.cnblogs.com/lizm166/p/8214696.html