生活随笔
收集整理的這篇文章主要介紹了
Python 网络爬虫笔记8 -- 股票数据定向爬虫
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Python 網絡爬蟲筆記8 – 股票數據定向爬蟲
Python 網絡爬蟲系列筆記是筆者在學習嵩天老師的《Python網絡爬蟲與信息提取》課程及筆者實踐網絡爬蟲的筆記。
課程鏈接:Python網絡爬蟲與信息提取
參考文檔:
Requests 官方文檔(英文)
Requests 官方文檔(中文)
Beautiful Soup 官方文檔
re 官方文檔
Scrapy 官方文檔(英文)
Scrapy 官方文檔(中文)
股票數據定向爬蟲
介紹:
- 爬取中國股市的股票信息
- 東方財富網:http://quote.eastmoney.com/stocklist.html
- 百度股票:https://gupiao.baidu.com/stock/
- 單個股票:https://gupiao.baidu.com/stock/sz002439.html
步驟:
從東方財富網獲取股票列表根據股票列表逐個到百度股票獲取個股信息根據股票列表逐個到百度股票獲取個股信息將結果存儲到文件將結果存儲到文件
import requests
from bs4 import BeautifulSoup
import redef get_html_text(url, code='utf-8'):"""獲取 HTML 頁面內容"""try:r = requests.get(url)r.raise_for_status()# r.encoding = r.apparent_encoding# 如果事先知道編碼,就不用從內容中分析編碼格式,提高運行速度r.encoding = codereturn r.textexcept:return ""def get_stocks_list(stock_list, stock_url):"""東方財富接口,爬取上證、深證所有上市公司的股票代碼"""html = get_html_text(stock_url, 'GB2312')soup = BeautifulSoup(html, 'html.parser')a = soup.find_all('a')for i in a:try:href = i.attrs['href']stock_list.append(re.findall(r's[hz]\d{6}', href)[0])except:continuedef get_stock_info(stock_list, stock_url, file_path):"""百度股票接口,根據股票的代碼爬取詳細信息"""count = 0for stock in stock_list:url = stock_url + stock + ".html"html = get_html_text(url)try:if html == "":continueinfo_dict = {}soup = BeautifulSoup(html, 'html.parser')# 找到股票信息的標簽stock_info = soup.find('div', attrs={'class': 'stock-bets'})# 股票信息的標簽中找到股票名字name = stock_info.find_all(attrs={'class': 'bets-name'})[0]info_dict.update({'股票名稱': name.text.split()[0]})# 股票的各種詳細信息key_list = stock_info.find_all('dt')value_list = stock_info.find_all('dd')for i in range(len(key_list)):key = key_list[i].text.strip()val = value_list[i].text.strip()info_dict[key] = valwith open(file_path, 'a', encoding='utf-8') as f:f.write(str(info_dict) + '\n')# 顯示當前進度count = count + 1print("\r當前進度: {:.2f}%".format(count*100/len(stock_list)),end="")except:count = count + 1print("\r當前進度: {:.2f}%".format(count * 100 / len(stock_list)), end="")continuedef main():"""爬取上市公司列表,根據列表爬取具體的信息,保存在文件中"""stock_list_url = 'http://quote.eastmoney.com/stocklist.html'stock_info_url = 'https://gupiao.baidu.com/stock/'output_file = 'E:/stocks.txt'stock_list = []get_stocks_list(stock_list, stock_list_url)get_stock_info(stock_list, stock_info_url, output_file)if __name__ == '__main__':print('running crawl_stocks')main()
總結
以上是生活随笔為你收集整理的Python 网络爬虫笔记8 -- 股票数据定向爬虫的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。