python代理ip关于设置proxies的问题

简介: python代理ip关于设置proxies的问题

前言


在进行Python开发时,经常会遇到被封IP或者频繁访问同一网站被限制访问等问题,这时,使用代理IP就可以避免这些问题,保证程序正常运行。本文将介绍如何使用Python设置代理IP,以及如何使用代理IP访问指定的网站。主要介绍通过urllib库实现网页访问时,如何通过设置代理IP来实现IP轮换等功能。


一、什么是代理IP?


代理IP是指通过代理服务器获取的IP地址,因为代理服务器具有隐藏用户真实IP、改变客户端访问地址、提高访问速度、突破访问限制等功能,所以使用代理IP可以实现一些数据获取的目的。


二、为什么需要设置代理IP?


在开发过程中,经常会遇到被封IP或者频繁访问同一网站被限制访问等问题。这时,使用代理IP就可以避免这些问题,保证程序正常运行。


三、如何设置代理IP?


在Python中,使用urllib库实现网页访问时,可以通过设置代理IP来实现IP轮换等功能。下面,我们以爬取某个网站为例,讲解如何设置代理IP。


首先,我们需要从免费的代理IP网站上获取代理IP,这里以站大爷代理为例,代码如下:

import requests
from bs4 import BeautifulSoup
 
def get_proxy():
    url = 'https://www.zdaye.com/free/'
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 Edge/16.16299'}
    r = requests.get(url, headers=headers)
    soup = BeautifulSoup(r.text, 'html.parser')
    table = soup.find('table', attrs={'id': 'ip_list'})
    proxies = []
    for row in table.tbody.find_all('tr'):
        if row.find_all('td')[4].string == 'HTTP':
            proxy = ':'.join([row.find_all('td')[1].string, row.find_all('td')[2].string])
            proxies.append(proxy)
    return proxies

上面的代码中,我们使用requests库访问站大爷代理网站,获取网页内容。然后,使用BeautifulSoup库解析网页内容,获取代理IP信息。

获取到代理IP后,我们需要测试这些代理IP是否可用,筛选出可用的代理IP。代码如下:

import requests
 
def test_proxy(proxy):
    url = 'https://www.baidu.com'
    proxies = {'http': 'http://' + proxy, 'https': 'https://' + proxy}
    try:
        r = requests.get(url, proxies=proxies, timeout=10)
        if r.status_code == 200:
            return True
        else:
            return False
    except:
        return False
 
def get_valid_proxies(proxies):
    valid_proxies = []
    for proxy in proxies:
        if test_proxy(proxy):
            valid_proxies.append(proxy)
    return valid_proxies

在上面的代码中,我们使用requests库通过代理IP访问百度网站,如果返回状态码为200,则说明代理IP可用。如果访问出现异常或者状态码不为200,则说明代理IP不可用。

获取到可用的代理IP后,我们就可以使用这些代理IP来访问指定的网站。代码如下:

import random
import requests
 
def get_html(url, proxies):
    proxy = random.choice(proxies)
    proxies = {'http': 'http://' + proxy, 'https': 'http://' + proxy}
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 Edge/16.16299'}
    try:
        r = requests.get(url, headers=headers, proxies=proxies, timeout=10)
        if r.status_code == 200:
            return r.text
        else:
            return None
    except:
        return None

上面的代码中,我们使用random库随机选择一个代理IP,然后使用requests库访问指定的网站。在访问时,需要将代理IP添加到proxies参数中,这样就可以使用代理IP来访问指定的网站了。


四、完整代码


import random
import requests
from bs4 import BeautifulSoup
 
def get_proxy():
    url = 'https://www.zdaye.com/free/'
    headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 Edge/16.16299'}
    r = requests.get(url, headers=headers)
    soup = BeautifulSoup(r.text, 'html.parser')
    table = soup.find('table', attrs={'id': 'ip_list'})
    proxies = []
    for row in table.tbody.find_all('tr'):
        if row.find_all('td')[4].string == 'HTTP':
            proxy = ':'.join([row.find_all('td')[1].string, row.find_all('td')[2].string])
            proxies.append(proxy)
    return proxies
 
def test_proxy(proxy):
    url = 'https://www.baidu.com'
    proxies = {'http': 'http://' + proxy, 'https': 'http://' + proxy}
    try:
        r = requests.get(url, proxies=proxies, timeout=10)
        if r.status_code == 200:
            return True
        else:
            return False
    except:
        return False
 
def get_valid_proxies(proxies):
    valid_proxies = []
    for proxy in proxies:
        if test_proxy(proxy):
            valid_proxies.append(proxy)
    return valid_proxies
 
def get_html(url, proxies):
    proxy = random.choice(proxies)
    proxies = {'http': 'http://' + proxy, 'https': 'http://' + proxy}
    headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 Edge/16.16299'}
    try:
        r = requests.get(url, headers=headers, proxies=proxies, timeout=10)
        if r.status_code == 200:
            return r.text
        else:
            return None
    except:
        return None
 
if __name__ == '__main__':
    url = 'https://www.baidu.com'
    proxies = get_proxy()
    valid_proxies = get_valid_proxies(proxies)
    html = get_html(url, valid_proxies)
    print(html)

在上面的代码中,我们首先定义了一个函数get_proxy(),用于获取代理IP。然后,定义了一个函数test_proxy(),用于测试代理IP是否可用。接下来,定义了一个函数get_valid_proxies(),用于获取可用的代理IP。最后,定义了一个函数get_html(),用于使用代理IP访问指定的网站,并返回HTML内容。


在主函数中,我们先访问西刺代理网站,获取代理IP信息。然后,使用get_valid_proxies()函数获取可用的代理IP。最后,使用get_html()函数访问百度网站,并输出返回内容。


总结

以上就是关于Python代理IP设置proxies的介绍,包括代理IP的概念、代理IP的设置和使用方法。在实际开发中,使用代理IP可以避免IP封禁等问题,提高效率和稳定性。


相关文章
|
13天前
|
Python
如何在Python中使用代理IP?
如何在Python中使用代理IP?
|
13天前
|
存储 API Python
python之代理ip的配置与调试
python之代理ip的配置与调试
|
13天前
|
API Python
怎么使用python检测代理IP是否有效
怎么使用python检测代理IP是否有效
|
12天前
|
存储 数据库 Python
使用Python编写代理IP自动切换技巧
使用Python编写代理IP自动切换技巧
|
13天前
|
Python
Python动态IP代理防止被封的方法
Python动态IP代理防止被封的方法
|
13天前
|
数据采集 存储 安全
python检测代理ip是否可用的方法
python检测代理ip是否可用的方法
|
11天前
|
数据挖掘 API 数据安全/隐私保护
python请求模块requests如何添加代理ip
python请求模块requests如何添加代理ip
|
14天前
|
缓存 中间件 数据安全/隐私保护
在Python中实现代理服务器的配置和使用方法
在Python中实现代理服务器的配置和使用方法
|
13天前
|
数据安全/隐私保护 Python
【Python】Python使用代理IP的实现
【Python】Python使用代理IP的实现
|
5月前
|
数据采集 监控 Python
Python创建代理IP池详细教程
Python创建代理IP池详细教程