python 爬虫怎么使用代理
在 Python 爬虫中使用代理,需要先获取代理 IP 和端口号,并将其设置为爬虫的请求头。下面是基本的使用步骤:
-
安装 requests 库和 BeautifulSoup 库。
-
获取代理 IP 和端口号,可以从以下网站获取:
- https://www.xicidaili.com/
- https://www.kuaidaili.com/
- https://www.ip3366.net/
-
将代理 IP 和端口号设置为 requests 库的代理参数,如下所示:
import requests proxies = { 'http': 'http://IP:PORT', 'https': 'https://IP:PORT' } response = requests.get(url, proxies=proxies) -
如果代理需要用户名和密码进行认证,则需要在代理参数中添加认证信息,如下所示:
proxies = { 'http': 'http://USERNAME:PASSWORD@IP:PORT', 'https': 'https://USERNAME:PASSWORD@IP:PORT' } -
如果需要使用多个代理 IP 进行轮换,可以使用代理池,例如使用 requests 库的 HTTPAdapter 和 urllib3 库的 PoolManager 实现代理池,如下所示:
import requests import urllib3 proxy_pool = urllib3.PoolManager() adapter = requests.adapters.HTTPAdapter(max_retries=3, pool_connections=100, pool_maxsize=100) session = requests.Session() session.mount('http://', adapter) session.mount('https://', adapter) def get_html(url): proxy = proxy_pool.urlopen('GET', 'http://IP:PORT', timeout=5.0) response = session.get(url, proxies={'http': proxy.data.decode()}, timeout=10.0) return response.text
以上是 Python 爬虫中使用代理的基本步骤,需要根据实际情况进行调整和优化
原文地址: http://www.cveoy.top/t/topic/htKT 著作权归作者所有。请勿转载和采集!