1、目标:获取上交所和深交所所有股票的名称和交易信息
2、输出:保存到文件中
3、技术路线:requests-bs4-re
4、网页选取原则:股票信息静态存在于HTML页面中,非js代码生成,没有Robots协议限制
5、选取方法:浏览器F12,源代码查看等
6、步骤:
①从东方财富网获取股票列表
②根据股票列表组个到百度股票获取个股信息
③将结果存储到文件
以下是MOOC的源代码,但是由于时间问题,这个代码已经不能用了,但是很有参考价值
import requests
from bs4 import BeautifulSoup
import traceback
import re
def getHTMLText(url, code="utf-8"):
try:
r = requests.get(url)
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')
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):
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="")
except:
count = count + 1
print("\r当前进度: {:.2f}%".format(count*100/len(lst)),end="")
continue
def main():
stock_list_url = 'https://quote.eastmoney.com/stocklist.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()
东方财富网股票列表网址:http://quote.eastmoney.com/stock_list.html
这是网页部分源码
个股信息我们可以在中财网获取:“http://quote.cfi.cn/quote_”+股票代码+".html"
这是我门需要提取的信息
以下是我重新编写的代码
import re
import requests
from bs4 import BeautifulSoup
import traceback
def getHtmlText(url):
try:
r = requests.get(url)
r.encoding = 'utf-8'
r.raise_for_status()
return r.text
except:
traceback.print_exc()
def getStockList(list,stocklurl):
html=getHtmlText(stocklurl)
soup=BeautifulSoup(html,"html.parser")
a = soup.find_all('a')
for i in a:
try:
href=i.attrs['href']
list.append(re.findall(r'[s][hz]\d{6}',href)[0])
except:
continue
def getStockInfo(list,stockIurl,path):
count = 0
for i in list[81:195]:
try:
code=re.findall(r'\d{6}',i) # findall返回一个列表类型
url = stockIurl + str(code[0]) + ".html"
html=getHtmlText(url)
if html=="":
continue
soup=BeautifulSoup(html,"html.parser")
InfoDict={}
na=soup.find('div',attrs={"id": "act_quote"})
if na is None:
continue
name=na.find('div',attrs={'class':'Lfont'}).string
InfoDict.update({'股票名称':name})
Information=na.find('table',attrs={'id':'quotetab'}) # find_all返回一个列表类型
# information=na.find('td',attrs={'class':'Rlist'})
tds=Information.find_all('td')
for item in tds:
text=item.get_text()
t_split=re.split(':|:',text)
key = t_split[0]
val = t_split[1]
real_val = re.search(r'(-?\d+.?\d*[%|手|万|元]?)|(--)|(正无穷大)', val).group(0)
InfoDict[key] = real_val
with open(path, 'a', encoding='utf-8') as f:
f.write(str(InfoDict) + '\n')
count = count + 1
print('\r当前速度:{:.2f}%'.format(count * 100 / len(list)), end="")
except:
count = count + 1
print('\r当前速度:{:.2f}%'.format(count * 100 / len(list)), end="")
traceback.print_exc()
continue
def main():
stock_list_url = 'http://quote.eastmoney.com/stock_list.html'
stock_info_url = 'http://quote.cfi.cn/quote_'
file_path = 'D://StockInfo1.txt'
InfoList=[]
getStockList(InfoList,stock_list_url)
getStockInfo(InfoList,stock_info_url,file_path)
main()
getStockInfo()函数中的部分代码参考了以下这篇文章
https://blog.csdn.net/Guanhai1617/article/details/104123303