筆者在做爬蟲作業時,遇到了一個動態網頁,分析代碼網頁源代碼時因此就少了許多需要的元素。下面用一個實例來記錄一下爬取動態網頁的步驟。
實例:股票定向爬蟲
這個實例目標是從東方財富網獲取股票列表,然後根據股票列表逐個到百度股票獲取個股信息,最後將結果存儲到文件。基本也看的出來代碼就是上面三個步驟。
踩雷
一開始沒發現這是個動態網頁,因爲我在需要的信息上面直接右鍵檢查,發現信息挺全的,但是代碼會變一下,當時也沒發現什麼不對(還是太菜了沒這實戰經驗),第一次操作如圖:
你可以看到,需要信息的網頁代碼還是存在的,但是當你展開td
標籤時,網頁會自動恢復,該標籤內部信息會自動收回,所以想到這是一個動態網頁,所有信息都是動態加載出來的,而非靜態呈現。右鍵查看源代碼,可以發現源代碼中並沒有這些信息,說明確實是動態網頁:
想想辦法
既然是動態加載的,那麼數據文件還是存在的。因此審查查看資源文件裏有沒有想要的數據文件,結果一個一個點開後發現了目標:
接着就直接點擊一個進去,複製url(右鍵 copy link address)看看是個什麼東西:
結果發現首頁所有的股票信息都在這個文件裏面,那麼很好,這個url就是我們爬取的對象url了。
代碼
- 解析網頁,返回源代碼
def getHTMLText(url, code='utf-8'):
try:
r = requests.get(url, timeout=30)
r.raise_for_status()
r.encoding = code
return r.text
except:
return ""
- 解析數據文件,使用re庫提取出股票信息
# 東方財富網,通過a標籤內找到股票標號,將所有的股票標號返回到lst中
def getStockList(lst, stockURL):
#2 sz 1 sh
html = getHTMLText(stockURL, "GB2312")
# soup = BeautifulSoup(html, 'html.parser')
content = re.findall(r"data:\[(.*?)\],recordsFiltered", html)[0]
#25
lists = content.split(",")
l=1
while l < len(lists):
if lists[l-1]=="\"2":
lst.append("sz"+ lists[l])
else:
lst.append("sh" + lists[l])
l+=26
- 根據股票信息,從百度股票獲取個股信息,並存放到文件中:
def getStockInfo(lst, stockURL, fpath):
count = 0 #進度
for stock in lst:
url = stockURL + stock + ".html" # https://gupiao.baidu.com/stock/sh000001.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
- main
if __name__ == '__main__':
stock_list_url = 'http://nufm.dfcfw.com/EM_Finance2014NumericApplication/JS.aspx?cb=jQuery1124042072564439236015_1553933614379&type=CT&token=4f1862fc3b5e77c150a2b985b12db0fd&sty=FCOIATC&js=(%7Bdata%3A%5B(x)%5D%2CrecordsFiltered%3A(tot)%7D)&cmd=C._A&st=(ChangePercent)&sr=-1&p=1&ps=20'
stock_info_url = 'https://gupiao.baidu.com/stock/'
output_file = 'D:\stack_info.txt'
slist = []
getStockList(slist, stock_list_url)
getStockInfo(slist, stock_info_url, output_file)
結果
就上一點點結果吧…