Python 爬虫代理

Python 爬虫代理

免责声明:自本文章发布起, 本文章仅供参考,不得转载,不得复制等操作。浏览本文章的当事人如涉及到任何违反国家法律法规造成的一切后果由浏览本文章的当事人自行承担与本文章博客主无关。以及由于浏览本文章的当事人转载,复制等操作涉及到任何违反国家法律法规引起的纠纷和造成的一切后果由浏览本文章的当事人自行承担与本文章博客主无关。

1. 基础知识

代理: 代理服务器, 代理 IP, 解决封 IP 的反爬机制.

代理的作用:

  1. 突破自身 IP 访问的限制.
  2. 隐藏自身真实 IP.

代理的网站:

  1. 快代理
  2. 西刺代理
  3. www.goubanjia.com

代理 IP 的类型:

  1. http: 应用到 http 协议对应的 URL 中.
  2. https: 应用到 https 协议对应的 URL 中.

代理 IP 的匿名度:

  1. 透明: 服务器知晓使用了代理, 且知道请求的真实 IP.
  2. 匿名: 服务器知晓使用了代理, 不知道请求的真实 IP.
  3. 高匿: 服务器不知晓使用了代理, 也不知道请求的真实 IP.

2. 例子

添加一个参数: proxies
我用本地虚拟机代理的.

#!/usr/bin/env python
# -*- coding: UTF-8 -*-

# 导包
import requests
from lxml import etree

if __name__ == '__main__':
    
    # 参数 url
    url = "http://2021.ip138.com/"
    headers = {
    
    
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:82.0) Gecko/20100101 Firefox/82.0",
        'Connection': 'close'
    }
    text = requests.get(url=url, headers=headers, timeout=15).text
    # 解析
    html = etree.HTML(text, etree.HTMLParser(encoding="utf-8"))
    xpath = html.xpath("//a//text()")[0]
    print(xpath)

    # 添加代理服务器
    proxies = {
    
    
        "http": "http://192.168.19.131:8080/",
        "https": "https://123.169.98.82:9999"
    }
    response = requests.get(url=url, headers=headers, proxies=proxies, timeout=30)
    response_text = response.text
    # 解析
    html_proxies = etree.HTML(response_text, etree.HTMLParser(encoding="utf-8"))
    xpath_proxies = html_proxies.xpath("//a/text()")[0]
    print(xpath_proxies)

在这里插入图片描述
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/YKenan/article/details/111997820