Python 利用代理IP爬取当当网数据做数据分析
本帖最后由 Shaw0xyz 于 2024-7-8 12:15 编辑1. 引言
爬取网站数据并进行数据分析是数据科学领域中常见的需求。由于网站通常会对频繁的爬取行为进行限制,使用代理IP是解决这一问题的有效方法。本文将详细介绍如何使用Python通过代理IP爬取当当网的数据,并进行简单的数据分析。
2. 准备工作
2.1 安装必要的库
在开始之前,需要安装一些必要的Python库,包括requests、BeautifulSoup和pandas。
可以通过以下命令安装这些库:
pip install requests
pip install beautifulsoup4
pip install pandas
2.2 获取代理IP
可以从一些代理IP提供商获取免费的代理IP。需要注意的是,免费代理IP的稳定性和速度可能不佳,可以根据需要选择付费的代理服务。
3. 爬取当当网数据
3.1 设置请求头和代理IP
为了模拟浏览器行为,避免被网站屏蔽,需要设置请求头信息。同时,需要配置代理IP。
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.3'
}
proxies = {
'http': 'http://your_proxy_ip:port',
'https': 'https://your_proxy_ip:port'
}
3.2 发送请求并解析页面
使用requests库发送请求,并使用BeautifulSoup解析页面内容。
import requests
from bs4 import BeautifulSoup
url = 'http://category.dangdang.com/cp01.54.00.00.00.00.html'
response = requests.get(url, headers=headers, proxies=proxies)
soup = BeautifulSoup(response.content, 'html.parser')
3.3 提取数据
从页面中提取需要的数据,如书名、作者、价格等。
books = []
for item in soup.select('.con .list_aa li'):
title = item.select('.name').get_text()
author = item.select('.publisher_info a').get_text()
price = item.select('.price .price_n').get_text()
books.append({
'title': title,
'author': author,
'price': price
})
4. 数据分析
4.1 数据清洗
将爬取的数据转换为pandas DataFrame,并进行数据清洗。
import pandas as pd
df = pd.DataFrame(books)
# 清洗价格数据,去掉“¥”符号,并转换为浮点数
df['price'] = df['price'].str.replace('¥', '').astype(float)
4.2 数据统计与可视化
进行简单的数据统计与可视化分析。
# 统计作者出现的频率
author_counts = df['author'].value_counts()
# 计算价格的均值和中位数
average_price = df['price'].mean()
median_price = df['price'].median()
# 可视化价格分布
import matplotlib.pyplot as plt
plt.hist(df['price'], bins=20)
plt.title('Price Distribution')
plt.xlabel('Price')
plt.ylabel('Frequency')
plt.show()
5. 错误处理与优化
在爬取过程中,可能会遇到各种错误,如请求超时、连接错误等。需要进行适当的错误处理,以提高爬取的稳定性。
try:
response = requests.get(url, headers=headers, proxies=proxies, timeout=10)
response.raise_for_status()
except requests.RequestException as e:
print(f"Error: {e}")
# 进行适当的处理,如重试、切换代理等
6. 结论
通过本文的介绍,读者可以了解如何使用Python通过代理IP爬取当当网的数据,并进行简单的数据分析。希望本文能帮助你更好地掌握网络爬虫和数据分析的技巧。如果有任何问题或建议,欢迎讨论交流。
/ 荔枝学姐de课后专栏 /
Hi!这里是荔枝学姐~
欢迎来到我的课后专栏
自然语言学渣 NLP摆烂姐
热衷于技术写作 IT边角料
AIGC & Coding & Linux ...
~互撩~ TG: @Shaw_0xyz
页:
[1]