第一步从东方财富网获取股票列表
第二步根据股票列表逐个到百度股票获取信息
第三步将所有文件打印到列表中
import requests
from bs4 import BeautifulSoup
import traceback
import re
def getHTMLText(url):
return “” /获取链接
def getStockList(lst, stockURL):
return “” /获取股票列表的网站
def getStockInfo(lst, stockURL, fpath):
return “” /储存的文件路径
def main(): /获取股票连接的主体
stock_list_url = ‘http://quote.eastmoney.com/stock_list.html’
stock_info_url = ‘http://stockpage.10jqka.com.cn/’
outout_file = ‘C://Users/zsnzd/Downloads/BaiduStickInfo.txt’
slist = []
getStockList(slist, stock_list_url)
getStockInfo(slist, stick_info_url, output_file)
main()
import requests
from bs4 import BeautifulSoup
import traceback
import re
def getHTMLText(url):
try:
r = requests.get(url, timeout = 30)
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 = getHTMLText(url)
try:
if html == “”: /出现空
continue
infoDict = {} / 定义字典存储信息
soup = BeautifulSoup(html, ‘html.parser’) /解析网页用soup
stockInfo = soupfind('div', attrs={'class':'m_content'})
/查找股票编码信息
name = stockInfo.find_all(attrs={'class':'m_header'})[0]
infoDict.update({'股票名称':name.text.split()[0]})
keyList = stockInfo.find_all('tr')
valueList = stockInfo.find_all('td')
for i in range(len(keyList)):/打印到列表
key = keyList[i].text
infoDick[key] = val
with open(fpath, 'a', encoding='utf-8') as f:
f.write(str(infoDict) + '\n')
except:
traceback.print_exc()
continue\获得异常
return ""
def main():
stock_list_url = ‘http://quote.eastmoney.com/stock_list.html’
stock_info_url = ‘http://stockpage.10jqka.com.cn/’
outout_file = ‘C://Users/zsnzd/Downloads/BaiduStickInfo.txt’
slist = []
getStockList(slist, stock_list_url)
getStockInfo(slist, stick_info_url, output_file)
main()