import requests
from bs4 import BeautifulSoup
import re
import time
def getHTMLText(url,code='utf-8'):
'''获得目标URL的HTML文本'''
r = requests.get(url,timeout=30)
r.raise_for_status()
r.encoding = code
return r.text
def getStockList(lst,stockURL):
'''从东方财富网获得目标URL的所有股票代码,并存入一个列表'''
try:
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
except:
print('getStockListerror')
def getStockInfo(lst,stockURL,fpath):
'''将获得的所有股票代码导入,然后依次根据各个股票代码在百度股票中获得各个股票的信息'''
count = 0
for stock in lst:
url = stockURL + stock +'.html'
try:
html = getHTMLText(url)
except:
count = count + 1
print('\r已完成:{:.2f}%'.format(count*100/len(lst)),end='')
continue
try:
if html =='':
count = count + 1
print('\r已完成:{:.2f}%'.format(count*100/len(lst)),end='')
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():
'''主函数'''
t = time.perf_counter()
stock_list_url = 'http://quote.eastmoney.com/stock_list.html'
stock_info_url = 'https://gupiao.baidu.com/stock/'
output_file = 'e://stockinfo1.txt'
slist = []
getStockList(slist,stock_list_url)
exclist = slist[:100]
print('共有',len(slist),'支股票')
getStockInfo(exclist,stock_info_url,output_file)
print('\n用时:{:.2f}s'.format(time.perf_counter()-t))
main()