python爬虫实战之旅( 第六章:代理)

上接:( 第五章:模拟登录+session对象+cookie值)
下接:(第七章:异步爬虫+梨视频爬取)

1.背景概要

1.1 IP反爬机制:

一般的门户网站会对每个访问的IP在一段时间内进行跟踪,如果这个IP的访问请求超出了一定的阈值,网站就会自动拦截这个IP的请求,并且断开信息的传送。

1.2 代理:

破解IP这种反爬机制

2.代理的概要

定义:
即代理服务器,就是网络信息中的一个中转站。

2.1代理的作用:

  • 突破自身IP访问的限制
  • 可以隐藏自身真实IP

2.2代理相关的网站:

  • 快代理
  • 西祠代理
  • http://ip.2993.net/
  • www.goubanjia.com
    在这里插入图片描述

2.3代理IP的类型:

  • http
  • https

2.4代理IP的匿名度:

  • 透明:服务器知道这次请求使用了代理,也知道请求对应的真实ip
  • 匿名:知道使用了代理,但不知道真实IP
  • 高匿名:不知道使用了代理,也不知道真实IP

3.代理在爬虫中的运用

很容易失败,先留个坑,我好像是网速太慢的问题
代码两个版本,第一个版本:

import requests
#UA伪装
headers={
    
    
    'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.11 Safari/537.36'
}
url='https://www.baidu.com/s?wd=IP'
page_text=requests.get(url=url,headers=headers,proxies={
    
    "https":'183.166.103.156:9999'}).text
with open('ip.html','w',encoding='utf-8') as fp:
    fp.write(page_text)

第二个版本:

#!/usr/bin/env python
# coding:utf-8

import requests
import json
import os
os.environ['http_proxy'] = 'http://127.0.0.1:1080'
os.environ['https_proxy'] = 'https://127.0.0.1:1080'

#UA伪装
headers={
    
    
    'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.11 Safari/537.36'
}
url='https://www.baidu.com/s?wd=IP'
response=requests.get(url=url,headers=headers)
print(response.status_code)
response_data=response.text

with open('daili.html','w',encoding='utf-8') as fp:
    fp.write(response_data)
    pass

猜你喜欢

转载自blog.csdn.net/KQwangxi/article/details/114261808