日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

Python 网络爬虫笔记8 -- 股票数据定向爬虫

發(fā)布時間:2025/3/12 python 14 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Python 网络爬虫笔记8 -- 股票数据定向爬虫 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

Python 網絡爬蟲筆記8 – 股票數(shù)據(jù)定向爬蟲


Python 網絡爬蟲系列筆記是筆者在學習嵩天老師的《Python網絡爬蟲與信息提取》課程及筆者實踐網絡爬蟲的筆記。

課程鏈接:Python網絡爬蟲與信息提取
參考文檔:
Requests 官方文檔(英文)
Requests 官方文檔(中文)
Beautiful Soup 官方文檔
re 官方文檔
Scrapy 官方文檔(英文)
Scrapy 官方文檔(中文)


股票數(shù)據(jù)定向爬蟲


介紹:

  • 爬取中國股市的股票信息
  • 東方財富網:http://quote.eastmoney.com/stocklist.html
  • 百度股票:https://gupiao.baidu.com/stock/
  • 單個股票:https://gupiao.baidu.com/stock/sz002439.html

步驟:

  • 從東方財富網獲取股票列表
  • 根據(jù)股票列表逐個到百度股票獲取個股信息根據(jù)股票列表逐個到百度股票獲取個股信息
  • 將結果存儲到文件將結果存儲到文件
  • 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):"""百度股票接口,根據(jù)股票的代碼爬取詳細信息"""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():"""爬取上市公司列表,根據(jù)列表爬取具體的信息,保存在文件中"""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 -- 股票数据定向爬虫的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。