python 爬虫 使用代理 爬取

之前有需要翻墙爬取内容,发现需要使用代理,不能简单的在requests里加个参数就行了,现在把脚本改成通用模板,有需要的可以按照自己的需求改一下哈。

import urllib.request as request
import requests
import json

'''
@author:Lancer Wu
@email:wxs231@163.com
'''


def proxies_spider(canshu):
    '''
    使用代理的爬虫
    :param canshu: 用字典包裹的参数
    canshu = {
        'url': 'url',
        'cookie': 'cookie',
        ……
    }
    :return:
    '''

    # 代理设置
    proxies = {
        'https': 'https://127.0.0.1:64708',  # 查找到你的vpn在本机使用的https代理端口
        'http': 'http://127.0.0.1:64708',  # 查找到vpn在本机使用的http代理端口
    }

    # 请求的链接
    url = canshu['url']

    # 请求的参数
    data = {
        'canshu1': canshu['canshu1'],
        'canshu2': canshu['canshu2'],
        'canshu3': canshu['canshu3']
    }

    # 请求的头部
    headers = {
        'user-agent': user_agent,  # 全局变量
        'Cookie': canshu['cookie']  # 有需要则传入cookie
    }

    # request增加代理设置
    opener = request.build_opener(request.ProxyHandler(proxies))
    request.install_opener(opener)

    # get请求
    req_result = requests.get(url=url, params=data, headers=headers, proxies=proxies)

    # post请求
    # req_result = requests.post(url=url, data=data, headers=headers, proxies=proxies)

    # 如果是html页面:
    req_result = req_result.text

    # 如果是json数据:
    # req_result = req_result.json()

    return req_result


if __name__ == "__main__":
    # 访问的浏览器信息
    user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) ' \
                 'Chrome/56.0.2924.87 Safari/537.36'

    canshu = {
        'url': '',  # 请求的链接
        'cookie': '',  # 请求的cookie,如果不需要可以留空
        'canshu1': 'data1',  # 请求的第一个参数
        'canshu2': 'data2',  # 请求的第二个参数
        'canshu3': 'data3'  # 请求的第三个参数
    }

    # 提交查询
    req_result = proxies_spider(canshu)
    print('req_result', req_result)

源码地址:
https://github.com/wuxs231/python_proxies_spider

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值