python 代理

使用代理

最近在http://weixin.sogou.com/折腾数据的时候碰到了ip被禁止访问的问题,所以想着是时候来一波代理的。以下是参考网上其他文章整理的:

class Proxy_Get(object):
    # 初始化函数
    def __init__(self):
        self.user_agent_list = [
            "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/22.0.1207.1 Safari/537.1",
            "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.6 (KHTML, like Gecko) Chrome/20.0.1092.0 Safari/536.6",
            "Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.6 (KHTML, like Gecko) Chrome/20.0.1090.0 Safari/536.6",
            "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/19.77.34.5 Safari/537.1",
            "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.9 Safari/536.5",
            "Mozilla/5.0 (Windows NT 6.0) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.36 Safari/536.5"
        ]
        self.ip_list = self.get()

    # 使用代理来处理请求
    def proxy_url(self, url):
        u_a = random.choice(self.user_agent_list)
        i_p = str(random.choice(self.ip_list)).strip()
        # # 这是代理IP
        proxy = {'http': i_p}
        print('\nu_a:', u_a, "\nproxy_ip:", i_p)
        # 创建ProxyHandler
        proxy_support = request.ProxyHandler(proxy)
        # 创建Opener
        opener = request.build_opener(proxy_support)
        # 安装OPener,使用install_opener方法之后,会将程序默认的urlopen方法替换掉。也就是说,如果使用install_opener之后,在该文件中,再次调用urlopen会使用自己创建好的opener
        request.install_opener(opener)

        # 添加User Angent
        req = request.Request(url)
        req.add_header('User-Agent', u_a)
        try:
            # 计时开始
            begin = time.time()
            # 使用自己安装好的Opener
            response = request.urlopen(req, timeout=5)
            speed = round(time.time() - begin, 2)
            print(speed)
            # 读取相应信息并解码
            html = response.read()
            return html
        except Exception as e:
            print(e)
            return self.proxy_url(url)

    # 从代理网站获取代理IP,返回IP集合
    def get(self):
        p_lists = []
        url = 'http://www.xicidaili.com/nn/'
        head = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1062.0 Safari/536.3'}
        req = request.Request(url, headers=head)
        response = request.urlopen(req)
        result = response.read()
        soup = BeautifulSoup(result, 'html.parser')

        # 常规查找,搞死人的节奏
        # # <table id="ip_list">
        # tr_lists = soup.find('table', id='ip_list').findAll('tr')
        # for tr in tr_lists:
        #     td_lists = tr.findAll('td')
        #     if td_lists is not None and len(td_lists) >= 7:
        #         p_lists.append(td_lists[1].get_text() + ":" + td_lists[2].get_text())

        # 优雅的使用正则匹配
        data = soup.find('table', id='ip_list').findAll('td')
        ip_compile = re.compile(r'<td>(\d+\.\d+.\d+.\d+)</td>')
        port_compile = re.compile(r'<td>(\d+)</td>')
        ip = re.findall(ip_compile, str(data))
        port = re.findall(port_compile, str(data))

        #此处太过python化,不太理解,下文补充
        p_lists = [":".join(i) for i in zip(ip, port)]
        print(p_lists)
        print(len(p_lists))
        return p_lists

# 单元测试用 
if __name__ == '__main__':
    p = Proxy_Get()
    start = 'http://www.baidu.com'
    res = p.proxy_url(start)
    print(res)

join的用法

join(): 连接字符串数组。将字符串、元组、列表中的元素以指定的字符(分隔符)连接生成一个新的字符串
自评:join使用指定字符重新拼接

#对序列进行操作(分别使用' '与':'作为分隔符)

>>> seq1 = ['hello','good','boy','doiido']
>>> print ' '.join(seq1)
hello good boy doiido
>>> print ':'.join(seq1)
hello:good:boy:doiido


#对字符串进行操作

>>> seq2 = "hello good boy doiido"
>>> print ':'.join(seq2)
h:e:l:l:o: :g:o:o:d: :b:o:y: :d:o:i:i:d:o


#对元组进行操作

>>> seq3 = ('hello','good','boy','doiido')
>>> print ':'.join(seq3)
hello:good:boy:doiido


#对字典进行操作

>>> seq4 = {'hello':1,'good':2,'boy':3,'doiido':4}
>>> print ':'.join(seq4)
boy:good:doiido:hello


#合并目录

>>> import os
>>> os.path.join('/hello/','good/boy/','doiido')
'/hello/good/boy/doiido'

zip使用

zip函数接受任意多个(包括0个和1个)序列作为参数,返回一个tuple列表。

1.示例1:

x = [1, 2, 3]
y = [4, 5, 6]
z = [7, 8, 9]
xyz = zip(x, y, z)
print xyz

运行的结果是:
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]

2.示例2:

x = [1, 2, 3]
y = [4, 5, 6, 7]
xy = zip(x, y)
print xy

运行的结果是:
[(1, 4), (2, 5), (3, 6)]
从这个结果可以看出zip函数的长度处理方式。

3.示例3

x = [1, 2, 3]
x = zip(x)
print x

结果是:
[(1,), (2,), (3,)]
从这个结果可以看出zip函数在只有一个参数时运作的方式。

4.示例4:

x = zip()
print x

运行的结果是:
[]
从这个结果可以看出zip函数在没有参数时运作的方式。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值