python真的特別適合處理字符串
而且python有大量的庫,如用來處理網頁的requests和 BeautifulSoup 庫
這次demo是用python爬取網易的股票網站
http://quotes.money.163.com/
直接上代碼,裏面的註釋很詳細。
代碼在這裏:點擊打開鏈接
代碼:
StaticStock.py
import requests
import re
from bs4 import BeautifulSoup
#### 第一題 ######################################
#調用requests來爬取網頁
url = 'http://quotes.money.163.com/0600795.html'#定義url
res = requests.get(url)
res.encoding = "utf-8" # 設置網頁編碼
# 字符串處理,得到 0600795.html
filename = url.split('/')[-1]
#保存網頁
fd = open(filename, 'w', encoding='utf-8', errors='ignore')
print(res.text, file=fd)
fd.close()
########## 第二題 ###########################
##調用BeautifulSoup來處理網頁
soup = BeautifulSoup(open(filename, encoding='utf-8'), "html.parser")
##找到類名爲 corp_info 的table
tag1 = soup.select(".corp_info")
ch = []
for child in tag1[0].strings:
ch.append(child)
##正則匹配,得到日期
mat = re.search(r"(\d{4}-\d{1,2}-\d{1,2})", (ch[19]))
##輸出日期
print('這一隻股票首次上市的時間:\n',mat.group())
############# 第三題 ################################
##調用requests來爬取網頁
url = 'http://quotes.money.163.com/trade/lsjysj_600795.html?year=2016&season=1'
res = requests.get(url)
res.encoding = "utf-8" # 設置網頁編碼
##正則表達式得到股票代號 年 季度
filename = url.split('/')[-1].split('?')
tem = filename[1].split('&')
##正則匹配
mat = re.search(r"(\d+)", (filename[0]))
##no 股票代號
no = mat.group()
mat = re.search(r"(\d+)", (tem[0]))
##year 年
year = mat.group()
mat = re.search(r"(\d+)", (tem[1]))
##season 季度
season = mat.group()
# print('year:',year,'\nsession',session,'\nno',no)
#根據題目要求,將這些分別連接起來,組成filename
filename = no + '_' + year + '_' + season + '.html'
##將數據存入文件
fd=open(filename,'w',encoding='utf-8',errors='ignore')
print(res.text,file=fd)
fd.close()
##調用BeautifulSoup來處理網頁
soup = BeautifulSoup(open(filename, encoding='utf-8'), "html.parser")
##利用class得到表格及其內容
table = soup.select(".table_bg001")[0]
table_child = table.children
table_content = [i for i in table_child]
##根據特徵,所有tr都大於200,所以可以根據這個特點,將需要的數據摘出來
list_tr = [i for i in table_content if len(str(i)) > 200]
##將子節點全部取出來,每一個tr就是一條數據
tr = [[i for i in list_tr[j].strings] for j in range(len(list_tr))]
#print(tr)
##利用列表解析和切片,得到規定要求的數據格式
dataPerTime = [(i[0], tuple(i[1:])) for i in tr]
import pickle
##將最後得到的數據有pickle保存,用eval還原即可使用
fd = open('./dataPerTime.txt', 'wb')
pickle.dump(str(dataPerTime), fd)
fd.close()
######### 第四題 #################################################################3
##循環讀入,直到-1結束
##然後會在命令行輸出想要的排序結果
key=int(input("請輸入你想要的排序順序:\n1:以日期爲序\n2:以成交量爲序\n3:以成交金額爲序\n.......\n如果沒有其他需求,-1結束\n"))
#當輸入一個數,且不是-1
while(key!=-1):
#處理邊界
if(key>11):#上界
key=1
if(key<-1 or key==0):#下界
key=1
###根據輸入的值,進行排序
dataSort=sorted(tr,key=lambda x:x[key-1])
##按照規定格式進行輸出
dataPerTimeSort = [(i[0], tuple(i[1:])) for i in dataSort]
for item in dataPerTimeSort:
print(item)
key=int(input("請輸入你想要的排序順序:\n1:以日期爲序\n2:以成交量爲序\n3:以成交金額爲序\n.......\n如果沒有其他需求,-1結束\n"))
DynamicStock.py
import requests
import re
#from requests.exceptions import ConnectionError
from bs4 import BeautifulSoup
#### 第六題 ################################################
##循環輸入,直到-1結束
key=int(input("請輸入你想要的查詢的股票代碼:如果沒有其他需求,-1結束\n"))
while(key!=-1):
##根據輸入,組合url
url='http://quotes.money.163.com/0'+str(key)+'.html'
#try:
##獲取網頁內容
res = requests.get(url)
res.encoding = "utf-8" # 設置網頁編碼
#print(r.status_code)
##如果股票代碼錯誤,那麼將會提示找不到,需要重新輸入
if(res.status_code==404):
key = int(input("你輸入的股票代碼查詢不到,請重新輸入,如果沒有其他需求,-1結束\n"))
#continue可以直接結束下面的內容,跳轉到while
continue
# 用bs4處理網頁結構
soup = BeautifulSoup(res.text, "html.parser")
table = soup.select(".corp_info")
table_child = []
for child in table[0].strings:
table_child.append(child)
##用正則表達式找到“上市日期”
mat = re.search(r"(\d{4}-\d{1,2}-\d{1,2})", (table_child[19]))
print('首次上市的時間:\n',mat.group())#
date=mat.group()
mat = re.search(r"(\d+)", (date))
##得到 year
year = int(mat.group())
##將得到的數據都保存到txt中,用excel打開
filename = './txt/'+str(key)+'.txt'
fd = open(filename, 'w', encoding='utf-8', errors='ignore')
print('正在下載,請稍等')
##做循環,year和season的二重循環,將所有數據得到
while(year<=2017):
#print('year: ',year)
for season in range(1,5):
#print('season: ', season)
#得到url
newUrl = 'http://quotes.money.163.com/trade/lsjysj_'+str(key)+'.html?year='+str(year)+'&season='+str(season)
#print(newUrl)
#得到網頁內容
newRes = requests.get(newUrl)
newRes.encoding = "utf-8" # 設置網頁編碼
##處理網頁結構
soup = BeautifulSoup(newRes.text, "html.parser")
##找到有數據的table
table_data = soup.select(".table_bg001")[0]
#print("table_data: ",table_data)
table_data_child = table_data.children
tchild = [i for i in table_data_child]
####根據特徵,所有tr都大於200,所以可以根據這個特點,將需要的數據摘出來
list_tr = [i for i in tchild if len(str(i)) > 200]
##將子節點全部取出來,每一個tr就是一條數據
tr = [[i for i in list_tr[j].strings] for j in range(len(list_tr))]
###將每一條數據都輸入到文本中,以\t分割
for dataPerTime in tr:
for ind in range(len(dataPerTime)):
print(dataPerTime[ind],file=fd,end='\t')
print(file=fd,end='\n')
##year累計,直到2017
year+=1
fd.close()
#600795
#1997 - 03 - 18
#print(r.text)
print('你需要的數據已經存入')
key = int(input("請輸入你想要的查詢的股票代碼:如果沒有其他需求,-1結束\n"))