跳到主要内容

金融数据分析(四)爬取股票数据——方法一:requests&bs4&re

· 2 分钟阅读
Allen Ma

项目二:用两种不同的方法爬取股票数据

方法一:requests&bs4&re

import requests
from bs4 import BeautifulSoup
import re


def getHTMLText(url, code="utf-8"):
kv = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36'}
try:
r = requests.get(url, headers=kv)
r.raise_for_status()
r.encoding = code
return r.text
except:
return ""


def getStockList(lst, stockURL):
html = getHTMLText(stockURL, "GB2312")
soup = BeautifulSoup(html, 'html.parser')
li = soup.find('section', attrs={'class': 'stockTable'})
a = li.find_all('a')
for i in a:
try:
href = i.attrs['href']
lst.append(re.findall(r"[S][HZ]\d{6}", href)[0])
except:
continue


def getStockInfo(lst, stockURL, fpath):
count = 0
for stock in lst:
url = stockURL + stock
html = getHTMLText(url)
try:
if html == "":
continue
infoDict = {}
soup = BeautifulSoup(html, 'html.parser')
stockInfo = soup.find('section', attrs={'class': 'stock_price clearfix'})
mc = soup.find('header', attrs={'class': 'stock_title'})
name = mc.find('h1')
infoDict.update({'股票名称': name.text})

keyList = stockInfo.find_all('dt')
valueList = stockInfo.find_all('dd')
for i in range(len(keyList)):
key = keyList[i].text
val = valueList[i].text
infoDict[key] = val

with open(fpath, 'a', encoding='utf-8_sig') as f:
f.write(str(infoDict) + '\n')
count = count + 1
print("\r当前进度: {:.2f}%".format(count * 100 / len(lst)), end="")
except:
count = count + 1
print("\r当前进度: {:.2f}%".format(count * 100 / len(lst)), end="")
continue


def main():
stock_list_url = 'https://hq.gucheng.com/gpdmylb.html'
stock_info_url = 'https://hq.gucheng.com/'
output_file = 'BaiduStockInfo.csv'
slist = []
getStockList(slist, stock_list_url)
getStockInfo(slist, stock_info_url, output_file)


main()

项目运行需要一段时间,可以通过输出台查看进度。

在这里插入图片描述 一个多小时后。。。执行完了 一共3590条数据 在这里插入图片描述