案例介绍
目标:获取上交所和深所所有股票的名称和交易信息
输出:保存到文件中
技术路线:requests-bs4-re
选取原则:股票信息静态存在于HTML页面中,非js代码生成,没有Robots协议限制。
选取方法:浏览器F12,源代码查看等。
选取心态:不要纠结于某个网站,多找信息源尝试。
案例编写
import requests
from bs4 import BeautifulSoup
import re
import traceback
# 获得url对应的页面
def getHTMLText(url):
try:
r = requests.get(url, timeout=30)
r.raise_for_status()
# r.encoding = r.apparent_encoding#编码识别的优化,手工的方式先获得编码的类型(apparent_encoding),然后直接赋给encoding
r.encoding = r.apparent_encoding
return r.text
except:
return ""
# 获得股票的信息列表
#第一个参数列表保存的列表类型,存储所有股票信息 第二个参数就是获得股票信息的URL网站
def getStockList(lst, stockURL):
html = getHTMLText(stockURL)
soup = BeautifulSoup(html, 'html.parser')
#找到a标签
a = soup.find_all('a')
#对a标签每一个进行遍历
for i in a:
try:
#上海交易所的股票以sh开头,深圳交易所股票以sz开头,股票数字以六位数字组成
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"
html = getHTMLText(url)
try:
if html == "":
continue
infoDict = {}
soup = BeautifulSoup(html, 'html.parser')
stockInfo = soup.find('div', attrs={'class': 'stock-bets'})
name = stockInfo.find_all(attrs={'class': 'bets-name'})[0]
infoDict.update({'股票名称': name.text.split()[0]})
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') as f:
f.write(str(infoDict) + '\n')
count = count + 1
print("\r当前进度:{:.2f}%".format(count * 100 / len(lst)), end=' ') # 增加动态的进度显示,
# \r能够将我们打印的字符串的最后的光标提到当前这一行的头部,下一次再进行相关打印的时候,
# 打印的信息就会覆盖之前打印的内容,这样实现了一个不换行的、动态变化的信息展示
except:
count = count + 1
print("\r当前进度:{:.2f}%".format(count * 100 / len(lst)), end=' ')
traceback.print_exc()
continue
def main():
#获得股票列表的链接
stock_list_url = 'http://quote.eastmoney.com/stock_list.html'
#获取股票信息的主体部分
stock_info_url = 'https://gupiao.baidu.com/stock/'
output_file = 'D://BaiduStockInfo.txt'
slist = []
#获得股票列表
getStockList(slist, stock_list_url)
#根据股票列表到相关网站上获取股票信息并储存到相关文件中
getStockInfo(slist, stock_info_url, output_file)
main()