首页 > python爬虫

Python爬虫设置ip代理过程解析

时间:2020-08-25 python爬虫 查看: 825

1、get方式:如何为爬虫添加ip代理,设置Request header(请求头)

import urllib 
import urllib.request
import urllib.parse
import random
import time
from fake_useragent import UserAgent
ua = UserAgent()
url = "http://www.baidu.com"
########################################################
'''
设置ip代理
iplist = [ '127.0.0.1:80']  #可自行上网找一些代理
proxy_support = urllib.request.ProxyHandler({'http':random.choice(iplist)}) #也可以设置为https,要看你的代理支不支持
opener = urllib.request.build_opener(proxy_support)
'''
########################################################
'''无ip代理'''
opener = urllib.request.build_opener()

'''f12查看请求头添加即可,不一定都需要全添加↓↓↓'''
opener.addheaders = [('Host', 'newtab.firefoxchina.cn'),
           ('User-Agent',ua.random),
           ('Accept-Encoding','deflate, br'),
           ('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'),
           ('Accept-Language', 'zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2'),
           ('Connection', 'keep-alive'),
           ('Upgrade-Insecure-Requests',1),
           ('Cookie', '__gads=ID=138080209be66bf8:T=1592037395:S=ALNI_Ma-g9wHmfxFL4GCy9veAjJrJRsNmg; Hm_lvt_dd4738b5fb302cb062ef19107df5d2e4=1592449208,1592471447,1592471736,1594001802; uid=rBADnV7m04mi8wRJK3xYAg=='),
          ]
urllib.request.install_opener(opener)
while True:
  try:
    response = urllib.request.urlopen(url)
    break
  except Exception as e:
    print("错误信息:" + str(e))
    time.sleep(3)
html = response.read().decode("utf-8")
print(html)

2、post方式添加载荷(此处是打比方),修改urllib.request.install_opener(opener)以下的代码即可

urllib.request.install_opener(opener)
# data = {}    #当页面提交数据是有载荷但是载荷内容为空时,必须以data = {}传参,不然无法获取网页数据
data = {'_csrf':'请把',
    'collection-name':'载荷的参数',
    'description':'以这种形式',
    '_csrf':'装载'
    }
data = urllib.parse.urlencode(data).encode('utf-8')
req = urllib.request.Request(url,data)
while True:
  try:
    response = urllib.request.urlopen(req)
    break
  except Exception as e:
    print("错误信息:" + str(e))
    time.sleep(3)
html = response.read().decode("utf-8")

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持python博客。

展开全文
上一篇:python3.7调试的实例方法
下一篇:Python爬虫实例——爬取美团美食数据
输入字:
相关知识
Python爬虫基础之爬虫的分类知识总结

来给大家讲python爬虫的基础啦,首先我们从爬虫的分类开始讲起,下文有非常详细的知识总结,对正在学习python的小伙伴们很有帮助,需要的朋友可以参考下

Python爬虫基础讲解之请求

今天带大家了解一下python爬虫的基础知识,文中有非常详细的解释说明,对正在学习python爬虫的小伙伴们有很好地帮助,需要的朋友可以参考下

PyQt5爬取12306车票信息程序的实现

12306是学习爬虫的比较好的一个练手网站。本文主要实现了PyQt5爬取12306车票信息程序,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

Python爬虫之m3u8文件里提取小视频的正确姿势

本文给大家分享如何正确提取m3u8文件里的.ts视频,并合成完整的.mp4格式视频,通过图文实例代码的形式给大家介绍的非常详细,对Python提取m3u8文件小视频感兴趣的朋友一起看看吧