爬取下拉加載的動態網頁信息

爬取的網站:http://blog.csdn.net/1024.html

需要爬取的信息如圖:


打開頁面源代碼,發現並沒有需要的信息,想起之前爬過的以json格式加載的網易評論,便開始點擊查看元素,篩選之後,知道只有藍色標註那個網址有所需要的內容,如圖。然後打開下圖的源代碼,神奇的東西出現了,在這裏,我截取了一部分,如下圖。


觀察每一部分源代碼,發現內容均在<div class="grid" id="">中,故打算用bs來寫代碼。

初始網址爲:http://blog.csdn.net/_1024/commentlist.html?id=15&type=0&ids=&r=0.5395537795144553&page=1

其中,r和page均爲變量,page有很強的規律性,表示頁數,而r並沒有什麼變化的規律,所以考慮將其刪掉,再打開網址時,發現沒有什麼影響,因此可以執行了。完整代碼如下。

# -*- coding:utf-8 -*-

from bs4 import BeautifulSoup
import  urllib2
import re

for i in range(1,92):
    url = 'http://blog.csdn.net/_1024/commentlist.html?id=15&type=0&ids=&page= % d' % i
    user_agent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:49.0) Gecko/20100101 Firefox/49.0"
    headers = {'User-Agent': user_agent}
    response = urllib2.Request(url, headers = headers)
    html = urllib2.urlopen(response).read()
    soup = BeautifulSoup(html, 'html.parser', from_encoding ='utf-8')
    content = soup.find_all( "div",class_ = "grid")
    for con in content:
        con = con.get_text('|',strip=True).encode('utf-8')
        con = con.replace('\n','')
        print con
        with open('nn.txt', 'a') as f:
            f.write( con + '\n' )
(由於網頁在不斷更新,故這裏的頁數不是固定值。)







發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章