文章目录
- import requests from bs4 import BeautifulSoup # 设置代理(格式:协议://IP:端口) proxies = { ‘http’: ‘http://123.45.67.89:8080’, ‘https’: ‘http://123.45.67.89:8080’ } headers = { ‘User-Agent’: ‘Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36’ } response = requests.get(‘https://www.zdaye.com/blog/article/just_changip’, proxies=proxies, headers=headers) soup = BeautifulSoup(response.text, ‘html.parser’) print(soup.title.text)
- import threading import time def fetch_data(url, proxy): try: response = requests.get(url, proxies={“http”: proxy}, timeout=10) if response.status_code == 200: print(f”Success with {proxy}”) # 处理数据… except: print(f”Failed with {proxy}”) # 付费代理池(示例) proxy_pool = [ ‘http://proxy1.com:8080’, ‘http://proxy2.com:8080’, # 添加更多代理… ] urls = [‘https://example.com/page1’, ‘https://example.com/page2’] # 创建线程池 threads = [] for url in urls: for proxy in proxy_pool: t = threading.Thread(target=fetch_data, args=(url, proxy)) threads.append(t) t.start() time.sleep(0.1) # 防止瞬间请求过多 # 等待所有线程完成 for t in threads: t.join()
- 在settings.py中配置: DOWNLOADER_MIDDLEWARES = { ‘scrapy.downloadermiddlewares.httpproxy.HttpProxyMiddleware’: 110, ‘myproject.middlewares.ProxyMiddleware’: 100, } PROXY_POOL = [ ‘http://user:pass@proxy1.com:8080’, ‘http://user:pass@proxy2.com:8080’, ] 创建中间件middlewares.py: import random class ProxyMiddleware: def process_request(self, request, spider): request.meta[‘proxy’] = random.choice(settings.get(‘PROXY_POOL’))
- 随机User-Agent:使用fake_useragent库生成浏览器特征 添加Referer:模拟页面跳转来源 设置Accept-Encoding:匹配常见压缩格式
- import time import random def safe_request(url): time.sleep(random.uniform(1,3)) # 随机等待1-3秒 return requests.get(url)
- # 使用Session保持会话 session = requests.Session() response = session.get(‘https://login.example.com’, proxies=proxies) # 处理登录后获取Cookie…
- import pandas as pd data = [] # 假设通过爬虫获取到items列表 for item in items: clean_item = { ‘title’: item[‘title’].strip(), ‘price’: float(item[‘price’].replace(‘$’, ”)), ‘date’: pd.to_datetime(item[‘date’]) } data.append(clean_item) df = pd.DataFrame(data) df.to_csv(‘output.csv’, index=False)
- import pymongo client = pymongo.MongoClient(‘mongodb://localhost:27017/’) db = client[‘mydatabase’] collection = db[‘products’] for item in items: collection.insert_one(item)
目录
- 一、基础概念解析
- 1.1 爬虫的工作原理
- 1.2 代理IP的作用
- 二、环境搭建与工具选择
- 2.1 Python库准备
- 2.2 代理IP选择技巧
- 三、实战步骤分解
- 3.1 基础版:单线程+免费代理
- 3.2 进阶版:多线程+付费代理池
- 3.3 终极版:Scrapy框架+自动切换代理
- 四、反爬对抗策略
- 4.1 请求头伪装
- 4.2 请求频率控制
- 4.3 Cookie处理
- 五、数据存储与处理
- 5.1 数据清洗
- 5.2 数据库存储
- 六、伦理与法律边界
- 七、性能优化技巧
- 结语
在数据驱动的时代,网络爬虫已成为获取信息的核心工具。当遇到目标网站的反爬机制时,代理IP就像"隐形斗篷",帮助爬虫突破限制。本文将用通俗的语言,带您掌握Python爬虫结合代理IP抓取数据的全流程。
想象成一只"数字蜘蛛",通过发送HTTP请求访问网页,获取HTML内容后解析出所需数据。Python的Requests库就像蜘蛛的"腿",BeautifulSoup和Scrapy框架则是它的"大脑"。
代理服务器就像"快递中转站",当您用Python发送请求时,请求会先到达代理服务器,再由代理转发给目标网站。这样目标网站看到的是代理的IP,而非您的真实地址。
requests:发送HTTP请求的"瑞士军刀"
beautifulsoup4:解析HTML的"手术刀"
scrapy:企业级爬虫的"重型装备"
安装命令:pip install requests beautifulsoup4 scrapy
免费代理:适合小规模抓取,但稳定性差(如西刺代理)
付费代理:提供高匿IP池,支持HTTPS(如站大爷、开心代理)
自建代理池:通过服务器搭建,灵活控制(需一定运维成本)
import requests
from bs4 import BeautifulSoup
# 设置代理(格式:协议://IP:端口)
proxies = {
'http': 'http://123.45.67.89:8080',
'https': 'http://123.45.67.89:8080'
}
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
}
response = requests.get('https://www.zdaye.com/blog/article/just_changip', proxies=proxies, headers=headers)
soup = BeautifulSoup(response.text, 'html.parser')
print(soup.title.text)
import threading
import time
def fetch_data(url, proxy):
try:
response = requests.get(url, proxies={"http": proxy}, timeout=10)
if response.status_code == 200:
print(f"Success with {proxy}")
# 处理数据...
except:
print(f"Failed with {proxy}")
# 付费代理池(示例)
proxy_pool = [
'http://proxy1.com:8080',
'http://proxy2.com:8080',
# 添加更多代理...
]
urls = ['https://example.com/page1', 'https://example.com/page2']
# 创建线程池
threads = []
for url in urls:
for proxy in proxy_pool:
t = threading.Thread(target=fetch_data, args=(url, proxy))
threads.append(t)
t.start()
time.sleep(0.1) # 防止瞬间请求过多
# 等待所有线程完成
for t in threads:
t.join()
在settings.py中配置:
DOWNLOADER_MIDDLEWARES = {
'scrapy.downloadermiddlewares.httpproxy.HttpProxyMiddleware': 110,
'myproject.middlewares.ProxyMiddleware': 100,
}
PROXY_POOL = [
'http://user:pass@proxy1.com:8080',
'http://user:pass@proxy2.com:8080',
]
创建中间件middlewares.py:
import random
class ProxyMiddleware:
def process_request(self, request, spider):
request.meta['proxy'] = random.choice(settings.get('PROXY_POOL'))
随机User-Agent:使用fake_useragent库生成浏览器特征
添加Referer:模拟页面跳转来源
设置Accept-Encoding:匹配常见压缩格式
import time
import random
def safe_request(url):
time.sleep(random.uniform(1,3)) # 随机等待1-3秒
return requests.get(url)
# 使用Session保持会话
session = requests.Session()
response = session.get('https://login.example.com', proxies=proxies)
# 处理登录后获取Cookie...
import pandas as pd
data = []
# 假设通过爬虫获取到items列表
for item in items:
clean_item = {
'title': item['title'].strip(),
'price': float(item['price'].replace('$', '')),
'date': pd.to_datetime(item['date'])
}
data.append(clean_item)
df = pd.DataFrame(data)
df.to_csv('output.csv', index=False)
import pymongo
client = pymongo.MongoClient('mongodb://localhost:27017/')
db = client['mydatabase']
collection = db['products']
for item in items:
collection.insert_one(item)
遵守robots.txt:检查网站根目录下的robots.txt文件
控制抓取频率:避免对目标服务器造成过大压力
尊重版权数据:不抓取涉及个人隐私或商业机密的信息
注明数据来源:在发布数据时明确标注抓取来源
异步IO:使用aiohttp库提升并发能力
分布式爬虫:结合Redis实现任务队列
缓存机制:对重复请求进行本地缓存
压缩传输:启用gzip/deflate压缩
通过Python爬虫与代理IP的组合,我们可以高效获取互联网上的公开信息。但技术始终是工具,合理使用才能创造价值。在享受数据便利的同时,请始终牢记:技术应该有温度,抓取需有底线。未来的智能抓取系统,将是效率与伦理的完美平衡。
到此这篇关于Python中高效抓取数据的实战指南的文章就介绍到这了,更多相关Python抓取数据内容请搜索风君子博客以前的文章或继续浏览下面的相关文章希望大家以后多多支持风君子博客!
您可能感兴趣的文章:
- 利用python抓取HTML页面数据并作可视化数据分析
- 利用Python抓取网页数据的多种方式与示例详解
- 利用Python进行网络爬虫和数据抓取的代码示例
- 使用python爬虫实现抓取动态加载数据
- Python网络请求使用Requests库抓取解析数据
- 使用Python和Scrapy实现抓取网站数据