# 如何使用Python爬取當當網所有數據分析書籍信息
## 目錄
1. [項目概述](#項目概述)
2. [技術準備](#技術準備)
3. [網頁結構分析](#網頁結構分析)
4. [爬蟲實現步驟](#爬蟲實現步驟)
5. [數據存儲方案](#數據存儲方案)
6. [反爬機制應對](#反爬機制應對)
7. [完整代碼實現](#完整代碼實現)
8. [數據分析應用](#數據分析應用)
9. [法律與倫理考量](#法律與倫理考量)
10. [總結與擴展](#總結與擴展)
---
## 項目概述
在數據驅動決策的時代,獲取圖書市場信息對從業者和研究者具有重要意義。本文將詳細介紹如何使用Python爬蟲技術,系統性地抓取當當網(www.dangdang.com)上所有與"數據分析"相關的圖書信息,包括但不限于:
- 書名、作者、出版社
- 價格信息(原價/折扣價)
- 出版日期、ISBN
- 用戶評分、評論數量
- 商品詳情頁的完整描述
---
## 技術準備
### 必需工具
```python
# 核心庫
import requests
from bs4 import BeautifulSoup
import pandas as pd
import time
import random
# 可選高級庫
from selenium import webdriver # 處理動態加載
import pymongo # MongoDB存儲
pip install requests beautifulsoup4 pandas selenium pymongo
當當網搜索URL示例:
http://search.dangdang.com/?key=數據分析&act=input&page_index=1
關鍵觀察:
1. 分頁參數:page_index
2. 每頁顯示60條結果
3. 數據加載方式:部分靜態HTML,部分動態AJAX
使用Chrome開發者工具(F12)分析:
- 書籍列表容器:ul.bigimg
> li
- 書名:a.pic
的title屬性
- 價格:span.search_now_price
- 評論數:span.search_comment_num
def get_page(url):
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36...'
}
try:
response = requests.get(url, headers=headers)
response.raise_for_status()
response.encoding = 'utf-8'
return response.text
except Exception as e:
print(f"請求失敗: {e}")
return None
def parse_list_page(html):
soup = BeautifulSoup(html, 'html.parser')
books = []
for item in soup.select('ul.bigimg li'):
try:
book = {
'title': item.select_one('a.pic')['title'],
'price': item.select_one('span.search_now_price').text.strip('¥'),
'author': item.select_one('p.search_book_author').text.split('/')[0].strip(),
'publisher': item.select_one('p.search_book_author').text.split('/')[-3].strip(),
'pub_date': item.select_one('p.search_book_author').text.split('/')[-2].strip(),
'comments': item.select_one('span.search_comment_num').text.strip('條評論'),
'detail_url': item.select_one('a.pic')['href']
}
books.append(book)
except Exception as e:
print(f"解析異常: {e}")
return books
def crawl_all_pages(keyword, max_pages=50):
base_url = "http://search.dangdang.com/?key={}&act=input&page_index={}"
all_books = []
for page in range(1, max_pages+1):
url = base_url.format(keyword, page)
print(f"正在抓取第{page}頁: {url}")
html = get_page(url)
if html:
books = parse_list_page(html)
if not books: # 無結果時終止
break
all_books.extend(books)
time.sleep(random.uniform(1, 3)) # 隨機延遲
return all_books
def save_to_csv(books, filename):
df = pd.DataFrame(books)
df.to_csv(filename, index=False, encoding='utf_8_sig')
def save_to_mongodb(books, db_name='dangdang', collection_name='books'):
client = pymongo.MongoClient('mongodb://localhost:27017/')
db = client[db_name]
collection = db[collection_name]
collection.insert_many(books)
proxies = {
'http': 'http://123.456.789.012:8888',
'https': 'https://123.456.789.012:8888'
}
response = requests.get(url, proxies=proxies)
# 完整代碼整合(包含異常處理、日志記錄等)
import logging
from tqdm import tqdm
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s'
)
def main():
keyword = "數據分析"
logging.info(f"開始抓取當當網[{keyword}]相關書籍")
try:
books = crawl_all_pages(keyword)
logging.info(f"共獲取到{len(books)}條數據")
# 存儲數據
save_to_csv(books, f'dangdang_{keyword}_books.csv')
save_to_mongodb(books)
logging.info("數據存儲完成")
except Exception as e:
logging.error(f"主程序異常: {e}", exc_info=True)
if __name__ == '__main__':
main()
df = pd.read_csv('dangdang_數據分析_books.csv')
# 價格分布分析
price_stats = df['price'].astype(float).describe()
# 出版社排行
publisher_top10 = df['publisher'].value_counts().head(10)
# 出版年份趨勢
df['year'] = df['pub_date'].str.extract(r'(\d{4})')
year_dist = df['year'].value_counts().sort_index()
import matplotlib.pyplot as plt
plt.figure(figsize=(12,6))
year_dist.plot(kind='bar')
plt.title('數據分析書籍出版年份分布')
plt.xlabel('年份')
plt.ylabel('數量')
plt.savefig('publication_trend.png')
注意:本文代碼僅供學習參考,實際使用時請遵守相關法律法規和網站規定。大規模商業用途需獲得平臺授權。 “`
(全文約3550字,實際字數可能因Markdown渲染方式略有差異)
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。