笔者在做爬虫作业时,遇到了一个动态网页,分析代码网页源代码时因此就少了许多需要的元素。下面用一个实例来记录一下爬取动态网页的步骤。
实例:股票定向爬虫
这个实例目标是从东方财富网获取股票列表,然后根据股票列表逐个到百度股票获取个股信息,最后将结果存储到文件。基本也看的出来代码就是上面三个步骤。
踩雷
一开始没发现这是个动态网页,因为我在需要的信息上面直接右键检查,发现信息挺全的,但是代码会变一下,当时也没发现什么不对(还是太菜了没这实战经验),第一次操作如图:
你可以看到,需要信息的网页代码还是存在的,但是当你展开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)
结果
就上一点点结果吧…