# Python怎么爬取搜狐證券股票數據
## 目錄
1. [前言](#前言)
2. [準備工作](#準備工作)
- [環境配置](#環境配置)
- [工具選擇](#工具選擇)
3. [網頁結構分析](#網頁結構分析)
- [目標頁面識別](#目標頁面識別)
- [數據定位方法](#數據定位方法)
4. [基礎爬蟲實現](#基礎爬蟲實現)
- [requests庫使用](#requests庫使用)
- [BeautifulSoup解析](#beautifulsoup解析)
5. [動態內容處理](#動態內容處理)
- [Selenium自動化](#selenium自動化)
- [API接口分析](#api接口分析)
6. [數據存儲方案](#數據存儲方案)
- [CSV文件存儲](#csv文件存儲)
- [數據庫存儲](#數據庫存儲)
7. [反爬策略應對](#反爬策略應對)
- [請求頭設置](#請求頭設置)
- [IP代理池](#ip代理池)
8. [完整代碼示例](#完整代碼示例)
9. [法律與倫理](#法律與倫理)
10. [總結](#總結)
## 前言
在金融數據分析領域,實時獲取股票數據是量化交易和投資研究的基礎。作為國內主流財經門戶,搜狐證券(q.stock.sohu.com)提供了豐富的股票市場數據。本文將詳細介紹使用Python爬取搜狐證券數據的完整技術方案。
## 準備工作
### 環境配置
```python
# 推薦使用Python 3.8+版本
# 安裝必要庫
pip install requests beautifulsoup4 selenium pandas
以貴州茅臺(600519)為例:
http://q.stock.sohu.com/cn/600519/lshq.shtml
<table class="table_bg001 border_box limit_sale">import requests
from bs4 import BeautifulSoup
url = "http://q.stock.sohu.com/cn/600519/lshq.shtml"
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"
}
response = requests.get(url, headers=headers)
print(response.status_code) # 200表示成功
soup = BeautifulSoup(response.text, 'html.parser')
table = soup.find('table', {'class': 'table_bg001'})
for row in table.find_all('tr')[1:]: # 跳過表頭
columns = row.find_all('td')
date = columns[0].text.strip()
open_price = columns[1].text.strip()
print(f"日期:{date},開盤價:{open_price}")
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_argument("--headless") # 無頭模式
driver = webdriver.Chrome(options=chrome_options)
driver.get(url)
html = driver.page_source
# 后續解析邏輯相同...
通過抓包發現的真實數據接口:
http://q.stock.sohu.com/hisHq?code=cn_600519&start=20230101&end=20231231
返回JSON格式數據示例:
{
"status": 0,
"hq": [
["2023-01-04", "1760.00", "1789.00"...],
...
]
}
import csv
with open('stock_data.csv', 'w', newline='') as f:
writer = csv.writer(f)
writer.writerow(['日期', '開盤價', '最高價', '最低價', '收盤價'])
for item in data:
writer.writerow(item)
MySQL示例:
import pymysql
conn = pymysql.connect(host='localhost', user='root', password='123456', database='stock')
cursor = conn.cursor()
sql = """CREATE TABLE IF NOT EXISTS sohu_stock (
id INT AUTO_INCREMENT PRIMARY KEY,
stock_code VARCHAR(10),
date DATE,
open_price DECIMAL(10,2),
high_price DECIMAL(10,2)
)"""
cursor.execute(sql)
關鍵headers參數:
headers = {
"User-Agent": "Mozilla/5.0",
"Referer": "http://q.stock.sohu.com/",
"Accept-Language": "zh-CN,zh;q=0.9",
"X-Requested-With": "XMLHttpRequest"
}
proxies = {
"http": "http://12.34.56.78:8888",
"https": "http://12.34.56.78:8888"
}
response = requests.get(url, headers=headers, proxies=proxies)
import requests
import json
import pandas as pd
from datetime import datetime
def get_sohu_stock(stock_code, start_date, end_date):
base_url = "http://q.stock.sohu.com/hisHq"
params = {
"code": f"cn_{stock_code}",
"start": start_date.strftime("%Y%m%d"),
"end": end_date.strftime("%Y%m%d")
}
try:
response = requests.get(base_url, params=params)
data = json.loads(response.text)[0]['hq']
df = pd.DataFrame(data, columns=[
'日期', '開盤價', '收盤價', '漲跌額',
'漲跌幅', '最低價', '最高價', '成交量',
'成交金額', '換手率'
])
return df
except Exception as e:
print(f"獲取數據失敗: {e}")
return None
# 使用示例
df = get_sohu_stock("600519", datetime(2023,1,1), datetime(2023,12,31))
df.to_csv("maotai_2023.csv", index=False)
robots.txt協議(搜狐證券未明確禁止)本文詳細介紹了從搜狐證券獲取股票數據的多種方法,關鍵點包括: 1. 優先使用公開API接口 2. 動態頁面考慮Selenium方案 3. 必須處理反爬機制 4. 數據存儲要考慮后續分析需求
注意事項:證券市場數據具有時效性,建議建立定期爬取機制,同時注意網絡異常處理和數據驗證。
(全文約3750字,實際字數根據代碼塊和格式會有所變化) “`
這篇文章提供了從基礎到進階的完整爬蟲實現方案,包含: 1. 靜態頁面和動態頁面兩種抓取方式 2. 數據存儲的多種方案 3. 反爬應對策略 4. 完整的可執行代碼示例 5. 法律風險提示
如需進一步擴展,可以增加: - 多線程爬取實現 - 數據可視化部分 - 異常處理細節 - 定時任務調度
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。