本文介紹作者如何爬取雪球網(wǎng)(https://xueqiu.com/)滬深股市滬深一覽中的上市公司日k線走勢圖并截圖保存至本地~
歡迎關(guān)注作者公眾號,追蹤更多更新更有價值的內(nèi)容。
一、前言
1.1 項目介紹
項目用于獲取雪球網(wǎng)滬深股市滬深一覽列表中(圖1)上市公司的日K線圖(圖2)。
圖1 滬深股市-滬深一覽
圖2?日K圖
以便從中獲取走勢向上的公司股票。
1.2 項目地址
項目gitee地址:https://gitee.com/shawn_chen_rtz/stock_daily_trend.git
1.3 環(huán)境準(zhǔn)備
需要安裝依賴requests、selenium模塊,通過pip命令。
pip install requests==2.27.1
pip?install selenium==3.141.0
二、代碼詳解
2.1 獲取股票名稱和股票代碼
創(chuàng)建方法獲取列表股票名稱和代碼,
import requests
def get_stocks():
sh_sz = []
for i in range(1, 11):
url = "https://stock.xueqiu.com/v5/stock/screener/quote/list.json?page=" + str(
i) + "&size=60&order=desc&orderby=percent&order_by=percent&market=CN&type=sh_sz"
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 \
(KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36",
"Cookie": "xqat=52dfb79aed5f2cdd1e7c2cfc56054ac1f5b77fc3"
}
try:
datas = requests.get(url, headers=headers).json()['data']['list']
except KeyError:
print("可能cookie中的xqat失效,請?zhí)鎿Q")
for data in datas:
sh_sz.append({'name': data['name'], 'code': data['symbol']})
return sh_sz
這里需要注意,請求的地址是https://stock.xueqiu.com/v5/stock/screener/quote/list.json?page=" + str(i)+"&size=60&order=desc&orderby=percent&order_by=percent&market=CN&type=sh_sz,其中str(i)是通過for循環(huán)變量i來控制獲取分頁數(shù)據(jù),例子中暫時硬編碼為1~10頁的數(shù)據(jù)。當(dāng)然也可以參數(shù)化,把分頁數(shù)量當(dāng)做方法get_stocks()的入?yún)?,可以自行?yōu)化。
另外需要注意的是,需要設(shè)置請求頭headers,否則不會返回正確響應(yīng)結(jié)果。其中尤其重要的是"Cookie"的設(shè)置,必不可少。"Cookie"的值可以通過瀏覽器訪問雪球網(wǎng)站獲取。
get_stocks()方法返回字典列表變量sh_sz。
2.2 根據(jù)股票代碼獲取日K線圖
思路:根據(jù)遍歷獲取的sh_sz,取其中的股票代碼拼成股票詳情鏈接,利用selenium訪問鏈接,關(guān)閉登錄彈窗后,點擊日K線,再對當(dāng)前瀏覽窗口進行截圖保存處理;
同時支持Win與Linux環(huán)境的執(zhí)行,可設(shè)置無頭模式執(zhí)行;支持日志記錄。
代碼實現(xiàn),如下,???????
from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.chrome.options import Options
import time
import logging
from get_stocks import get_stocks
LOG_FORMAT = "%(levelname)s %(asctime)s - %(message)s"
logging.basicConfig(filename='stock_snapshot.log', level=logging.INFO, filemode='a', format=LOG_FORMAT)
logger = logging.getLogger()
# linux webdriver路徑
# driver_path = "/usr/bin/chromedriver"
# Windows webdriver路徑
driver_path = "D:\webdriver\chromedriver.exe"
# 是否設(shè)置為無頭瀏覽模式
head_less = True
if head_less:
chrome_options = Options()
chrome_options.add_argument("--headless")
chrome_options.add_argument("--no-sandbox")
driver = webdriver.Chrome(driver_path, chrome_options=chrome_options)
else:
driver = webdriver.Chrome(driver_path)
stocks = get_stocks()
for stock in stocks:
driver.maximize_window()
driver.get(f"https://xueqiu.com/S/{stock['code']}")
# 關(guān)閉掉登錄提示窗
login_win = driver.find_element_by_class_name("modal__login")
action = ActionChains(driver)
action.move_to_element(login_win).perform()
close = login_win.find_element_by_class_name('close')
driver.execute_script('arguments[0].click();', close)
# 切換日線
chart_period_ls = driver.find_elements_by_class_name("chart-period-list")
for chart in chart_period_ls:
if chart.text.strip() == "日K":
# chart.click()
driver.execute_script('arguments[0].click();', chart)
time.sleep(0.6)
driver.set_window_size(1200, 820)
driver.get_screenshot_as_file(f"{stock['name']}.png")
logger.info(f"{stock['name']}日線走勢圖片保存成功")
重點在于登錄提示窗的關(guān)閉、日K線的點擊與圖片快照保存,都是通過Python?selenium模塊實現(xiàn)。而selenium是一種支持多編程語言的自動化測試框架,關(guān)于其詳細介紹,請訪問其官方網(wǎng)站https://www.selenium.dev/。
三、執(zhí)行結(jié)果
3.1 執(zhí)行結(jié)果
執(zhí)行項目,
在項目目錄下生成一系列股票日K線快照。除此之外還有很多的功能值得增加、擴展。歡迎留言~文章來源:http://www.zghlxwxcb.cn/news/detail-846451.html
可以關(guān)注作者微信公眾號,追蹤更多有價值的內(nèi)容!文章來源地址http://www.zghlxwxcb.cn/news/detail-846451.html
到了這里,關(guān)于利用Python和Selenium獲取雪球網(wǎng)滬深上市公司日k線走勢圖的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!