Python爬虫学习笔记(使用代理及代理池——解决返回状态码302即IP被封的问题)

对于一般的小型爬虫,我们爬取某个网站所发出的请求次数少即频率不是很高时,为避免可能出现的IP被封的问题,我们可以设置爬取延时或者规定爬取时长来解决。

1.requests库

import requests
#如果代理需要认证,可以使用proxy='username:password@IP:port'
proxyHttps = '121.33.220.158' #端口:808
proxyHttp = '110.73.8.171' #端口:8123

url = 'http://httpbin.org/get'
proxies={
    'http':'http://'+proxyHttp+':8123',
    'https':'https://'+proxyHttps+'808'
}
'''
    socks5代理使用,首先使用pip安装requests[socks]模块
    proxies={
        'http':'socks5://'+proxy+':port'
        'https':'socks5://'+proxy+':port'
    }
'''
try:
    re = requests.get(url,proxies)
    print(re.text)
except requests.exceptions.ConnectionError as e:
    print('ERROR',e.args)

 

2.selenium+Headless

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

url = 'http://httpbin.org/get'
service_args=[
    '--proxy=110.73.8.171:8123',
    '--proxy-type=http'
]

# 声明谷歌浏览器对象
#driver = webdriver.Chrome()
#设置浏览器无头模式
option = webdriver.ChromeOptions()
option.add_argument('--headless')
option.add_argument('--disable-gpu') #禁用 GPU 硬件加速,防止出现bug
driver = webdriver.Chrome(options=option,service_args=service_args)
driver.get(url)
print(driver.page_source)

 

3.代理池的使用

网络上有很多已经封装好的代理池工程可以使用,这里使用此代理池工程,此代理池爬取免费代理网站中的代理IP和端口(获取模块),动态判断其有效性(检测模块)并将有效的代理保存到本地的Redis数据库(存储模块,注意修改自己的端口和密码,具体参见这篇博客),最后建立接口以webAPI的形式暴露可用代理(接口模块),通过接口程序可以动态获取可用代理。使用时首先保持本地redis数据库开启并连接,然后运行代理池工程,最后 运行爬虫工程即可

import requests

PROXY_POOL_URL = 'http://localhost:5555/random' #获取代理IP及端口的URL,此URL暴露随机的可用代理IP

def get_proxy():
    try:
        respo = requests.get(PROXY_POOL_URL) #获取代理IP及端口
        if respo.status_code == 200:
            return respo.text
    except ConnectionError:
        return None

def use_proxy(getProxy):
    proxy = getProxy
    proxies = {
        'http':'http://'+proxy,
        'https': 'https://' + proxy
    }
    try:
        response = requests.get('http://httpbin.org/get',proxies=proxies)
        print(response.text)
    except requests.exceptions.ConnectionError as e:
        print('Erroe',e.args)

def main():
    getProxy = get_proxy()
    use_proxy(getProxy)

main()

4.付费代理推荐:阿布云代理(动态版),提供各种爬虫库的接入方式

5.ADSL拨号代理推荐:云立方

你可能感兴趣的:(Python爬虫)