功能描述:获取上交所和深交所所有股票的名称和交易信息,将输出保存到文件中
候选数据网站的选择原则:股票信息需静态存在于HTML页面中,非js代码生成没有Robots协议限制。
步骤:
1.从东方财富网获取股票列表
2.根据股票列表逐个到百度股票获取个股信息
3.将结果储存到文件
import requests
from bs4 import BeautifulSoup
import traceback
import re
def getHTMLText(url):
try:
r=requests.get(url)
r.raise_for_status()
#r.encoding=r.apparent_encoding
return r.text
except:
return ""
def getStockList(lst,stockURL):
html=getHTMLText(stockURL)
soup=BeautifulSoup(html,'html.parser')
a=soup.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):
for stock in lst:
url=stockURL+stock+".html"