# Python中怎么利用requests爬取百度貼吧用戶信息
## 目錄
1. [前言](#前言)
2. [準備工作](#準備工作)
- [環境配置](#環境配置)
- [分析目標](#分析目標)
3. [基礎爬蟲實現](#基礎爬蟲實現)
- [獲取網頁內容](#獲取網頁內容)
- [解析用戶信息](#解析用戶信息)
4. [高級技巧](#高級技巧)
- [處理分頁](#處理分頁)
- [應對反爬機制](#應對反爬機制)
5. [數據存儲](#數據存儲)
- [CSV文件存儲](#csv文件存儲)
- [數據庫存儲](#數據庫存儲)
6. [完整代碼示例](#完整代碼示例)
7. [注意事項](#注意事項)
8. [總結](#總結)
---
## 前言
百度貼吧作為中文互聯網最大的社區平臺之一,蘊含大量用戶生成內容。通過Python的requests庫爬取用戶信息,可以幫助進行社交網絡分析、用戶行為研究等。本文將詳細介紹如何從零開始構建一個貼吧用戶信息爬蟲。
---
## 準備工作
### 環境配置
```python
# 所需庫安裝
pip install requests beautifulsoup4 lxml pandas
requests:網絡請求庫beautifulsoup4:HTML解析庫lxml:解析器(比Python內置解析器更快)pandas:數據存儲處理以”李毅吧”為例,我們需要獲?。?1. 用戶昵稱 2. 發帖時間 3. 發帖內容 4. 用戶等級 5. 發帖IP屬地(2022年后新增字段)
打開瀏覽器開發者工具(F12),觀察貼吧頁面的網絡請求:

關鍵發現:
- 數據通過異步接口加載
- 用戶信息包含在data-content屬性中
- 分頁參數為pn
import requests
from bs4 import BeautifulSoup
def get_page(page_num):
url = f"https://tieba.baidu.com/f?kw=李毅&pn={(page_num-1)*50}"
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 requests.exceptions.RequestException as e:
print(f"請求失敗: {e}")
return None
def parse_user_info(html):
soup = BeautifulSoup(html, 'lxml')
posts = soup.find_all('div', class_='threadlist_bright')
user_data = []
for post in posts:
try:
author = post.find('a', class_='frs-author-name').text.strip()
level = post.find('span', class_='frs-author-level').text.strip()
content = post.find('div', class_='threadlist_abs').text.strip()
time = post.find('span', class_='threadlist_reply_date').text.strip()
# 2023年新增IP屬地解析
ip_loc = post.find('span', class_='ip_loc').text if post.find('span', class_='ip_loc') else '未知'
user_data.append({
'author': author,
'level': level,
'content': content,
'time': time,
'ip_location': ip_loc
})
except AttributeError as e:
print(f"解析出錯: {e}")
continue
return user_data
def crawl_multiple_pages(start_page, end_page):
all_data = []
for page in range(start_page, end_page+1):
print(f"正在爬取第{page}頁...")
html = get_page(page)
if html:
page_data = parse_user_info(html)
all_data.extend(page_data)
time.sleep(2) # 禮貌性延遲
return all_data
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)",
"Referer": "https://tieba.baidu.com/",
"Cookie": "你的登錄Cookie(如需)"
}
proxies = {
'http': 'http://12.34.56.78:8888',
'https': 'https://12.34.56.78:8888'
}
response = requests.get(url, headers=headers, proxies=proxies)
try:
response = requests.get(url, timeout=10)
if response.status_code == 403:
print("觸發反爬,需要更換IP或Cookie")
elif '驗證碼' in response.text:
print("需要人工干預驗證碼")
except requests.exceptions.Timeout:
print("請求超時")
import pandas as pd
def save_to_csv(data, filename):
df = pd.DataFrame(data)
df.to_csv(filename, index=False, encoding='utf_8_sig')
import sqlite3
def save_to_db(data, db_name='tieba_users.db'):
conn = sqlite3.connect(db_name)
c = conn.cursor()
# 創建表
c.execute('''CREATE TABLE IF NOT EXISTS users
(author TEXT, level TEXT, content TEXT, time TEXT, ip_location TEXT)''')
# 批量插入
to_insert = [(d['author'], d['level'], d['content'], d['time'], d['ip_location'])
for d in data]
c.executemany("INSERT INTO users VALUES (?,?,?,?,?)", to_insert)
conn.commit()
conn.close()
# tieba_spider.py
import requests
from bs4 import BeautifulSoup
import time
import pandas as pd
import sqlite3
class TiebaSpider:
def __init__(self, tieba_name):
self.tieba_name = tieba_name
self.base_url = f"https://tieba.baidu.com/f?kw={tieba_name}"
self.headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"
}
def get_page(self, page_num):
url = f"{self.base_url}&pn={(page_num-1)*50}"
try:
response = requests.get(url, headers=self.headers)
response.raise_for_status()
return response.text
except Exception as e:
print(f"Error fetching page {page_num}: {e}")
return None
def parse_page(self, html):
# 解析邏輯同上
pass
def run(self, start_page=1, end_page=5):
all_data = []
for page in range(start_page, end_page+1):
print(f"Crawling page {page}...")
html = self.get_page(page)
if html:
all_data.extend(self.parse_page(html))
time.sleep(1.5)
return all_data
if __name__ == "__main__":
spider = TiebaSpider("李毅")
data = spider.run(1, 3)
pd.DataFrame(data).to_csv("liyi_users.csv", index=False)
法律合規性
技術限制
道德規范
通過本文我們實現了: 1. 使用requests獲取貼吧頁面 2. 用BeautifulSoup解析用戶信息 3. 處理分頁和反爬措施 4. 多種數據存儲方式
進階方向: - 使用Scrapy框架提高效率 - 結合Selenium處理動態內容 - 構建分布式爬蟲系統 - 進行用戶社交網絡圖譜分析
最后提醒:技術應當用于正當用途,請在法律和道德框架內合理使用爬蟲技術。 “`
注:實際使用時需要: 1. 替換示例中的圖片鏈接為真實截圖 2. 根據最新貼吧頁面結構調整解析邏輯 3. 添加更完善的異常處理 4. 建議先小規模測試再擴大爬取范圍
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。