python網路爬蟲抓取動態網頁並將資料存入資料庫MySQL

來源:互聯網
上載者:User

標籤:highlight   report   query   none   firebug   響應   tco   2.7   name   

簡述

以下的代碼是使用python實現的網路爬蟲,抓取動態網頁 http://hb.qq.com/baoliao/ 。此網頁中的最新、精華下面的內容是由JavaScript動態產生的。審查網頁元素與網頁源碼是不同。

以上是網頁源碼

以上是審查網頁元素

所以此處不能簡單的使用Regex來擷取內容。

以下是完整的擷取內容並儲存到資料庫的思路及源碼。

實現思路:

抓取實際訪問的動態網頁面的url – 使用Regex擷取需要的內容 – 解析內容 – 儲存內容

以上部分過程文字解釋:

抓取實際訪問的動態網頁面的url:

在Firefox瀏覽器中,右鍵開啟外掛程式 使用**firebug審查元素** *(沒有這項的,要安裝firebug外掛程式),找到並開啟**網路(NET)**標籤頁。重新載入網頁,獲得網頁的響應資訊,包括串連地址。每個串連地址都可以在瀏覽器中開啟。本網站的動態網頁訪問地址是:http://baoliao.hb.qq.com/api/report/NewIndexReportsList/cityid/18/num/20/pageno/1?callback=jQuery183019859437816181613_1440723895018&_=1440723895472

  

Regex:

Regex的使用有兩種思路,可以參考個人有關其簡述:python實現簡單爬蟲以及Regex簡述 
更多的細節介紹可以參考網上資料,搜尋關鍵詞: Regex python

json:

參考網上有關json的介紹,搜尋關鍵詞: json python

儲存到資料庫:

參考網上的使用介紹,搜尋關鍵詞: 1,mysql 2,mysql python

源碼及注釋

注意:使用python的版本是 2.7

 

#!/usr/bin/python#指明編碼# -*- coding: UTF-8 -*- #匯入python庫import urllibimport urllib2import reimport MySQLdbimport json#定義爬蟲類class crawl1:         def getHtml(self,url=None):        #代理        user_agent="Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.0"        header={"User-Agent":user_agent}        request=urllib2.Request(url,headers=header)        response=urllib2.urlopen(request)        html=response.read()        return html    def getContent(self,html,reg):        content=re.findall(html, reg, re.S)        return content     #串連資料庫 mysql    def connectDB(self):        host="192.168.85.21"        dbName="test1"        user="root"        password="123456"        #此處添加charset=‘utf8‘是為了在資料庫中顯示中文,此編碼必須與資料庫的編碼一致        db=MySQLdb.connect(host,user,password,dbName,charset=‘utf8‘)        return db        cursorDB=db.cursor()        return cursorDB      #建立表,SQL語言。CREATE TABLE IF NOT EXISTS 表示:表createTableName不存在時就建立    def creatTable(self,createTableName):        createTableSql="CREATE TABLE IF NOT EXISTS "+ createTableName+"(time VARCHAR(40),title VARCHAR(100),text  VARCHAR(40),clicks VARCHAR(10))"         DB_create=self.connectDB()        cursor_create=DB_create.cursor()        cursor_create.execute(createTableSql)        DB_create.close()        print ‘creat table ‘+createTableName+‘ successfully‘              return createTableName     #資料插入表中    def inserttable(self,insertTable,insertTime,insertTitle,insertText,insertClicks):        insertContentSql="INSERT INTO "+insertTable+"(time,title,text,clicks)VALUES(%s,%s,%s,%s)"#         insertContentSql="INSERT INTO "+insertTable+"(time,title,text,clicks)VALUES("+insertTime+" , "+insertTitle+" , "+insertText+" , "+insertClicks+")"        DB_insert=self.connectDB()        cursor_insert=DB_insert.cursor()                cursor_insert.execute(insertContentSql,(insertTime,insertTitle,insertText,insertClicks))        DB_insert.commit()        DB_insert.close()        print ‘inert contents to  ‘+insertTable+‘ successfully‘  url="http://baoliao.hb.qq.com/api/report/NewIndexReportsList/cityid/18/num/20/pageno/1?callback=jQuery183019859437816181613_1440723895018&_=1440723895472"#Regex,擷取js,時間,標題,常值內容,點擊量(瀏覽次數)reg_jason=r‘.*?jQuery.*?\((.*)\)‘reg_time=r‘.*?"create_time":"(.*?)"‘reg_title=r‘.*?"title":"(.*?)".*?‘reg_text=r‘.*?"content":"(.*?)".*?‘reg_clicks=r‘.*?"counter_clicks":"(.*?)"‘#執行個體化crawl()對象crawl=crawl1()html=crawl.getHtml(url)html_jason=re.findall(reg_jason, html, re.S)html_need=json.loads(html_jason[0])print len(html_need)print len(html_need[‘data‘][‘list‘])table=crawl.creatTable(‘yh1‘)for i in range(len(html_need[‘data‘][‘list‘])):    creatTime=html_need[‘data‘][‘list‘][i][‘create_time‘]    title=html_need[‘data‘][‘list‘][i][‘title‘]    content=html_need[‘data‘][‘list‘][i][‘content‘]    clicks=html_need[‘data‘][‘list‘][i][‘counter_clicks‘]    crawl.inserttable(table,creatTime,title,content,clicks) 

 

python網路爬蟲抓取動態網頁並將資料存入資料庫MySQL

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.