欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

下載糗事百科的內(nèi)容_python版

 更新時間:2008年12月07日 20:02:27   作者:  
代碼是沒問題的,可以正常運行,但是希望做到以下2方面: 1、多線程下載 2、代碼分離度更高,跟面向?qū)ο?
復制代碼 代碼如下:

#coding:utf-8

import urllib.request
import xml.dom.minidom
import sqlite3
import threading
import time

class logger(object):
def log(self,*msg):
for i in msg:
print(i)

Log = logger()
Log.log('測試下')

class downloader(object):

def __init__(self,url):
self.url = url

def download(self):
Log.log('開始下載',self.url)
try:
content = urllib.request.urlopen(self.url).read()
#req = urllib.request.Request(url)
#response = urllib.request.urlopen(req)
#content = response.read()
Log.log('下載完畢')
return(content)
except:
Log.log('下載出錯')
return(None)


class parser(object):

def __init__(self,content):
#獲得根節(jié)點
self.html = xml.dom.minidom.parseString(content)

def parse(self):
Log.log('開始提取數(shù)據(jù)')
contents = {'content':'','url':[]}
#獲得div節(jié)點
divs = self.html.getElementsByTagName('div')
#獲得content節(jié)點
for div in divs:
if div.hasAttribute('class') and \
div.getAttribute('class') == 'content':
#獲得糗事百科的內(nèi)容
textNode = div.childNodes[0]
qContent = textNode.data
#數(shù)據(jù)填充
contents['content'] = qContent

#獲得上一糗事、下一糗事節(jié)點
spans = self.html.getElementsByTagName('span')
for span in spans:
pspan = span.parentNode
if pspan.tagName == 'a':
#pspan為對應的鏈接,此時需要將對應的地址加入數(shù)據(jù)庫
url = pspan.getAttribute('href')
qid = url[10:][:-4]
#數(shù)據(jù)填充
contents['url'].append(qid)
Log.log('提取數(shù)據(jù)完畢')
return(contents)

def downloadPage(qid,db):
url = 'http://www.qiushibaike.com/articles/'+str(qid)+'.htm'
content = downloader(url).download()
if content:
contents = parser(content).parse()
if contents['content']:
db.updateContent(qid,contents['content'])
for i in contents['url']:
db.addQID(i)
if len(contents['url']) == 2:
db.updateStatus(qid,2)

#下載池,表示同時允許下載的鏈接個數(shù)
class downloaderPool(object):
def __init__(self,maxLength=15):
self.downloaders = [None]*maxLength
self.downloadList = []
self.db = None

def setDownloadList(self,downloadList):
self.downloadList = list(set(self.downloadList+downloadList))

def setdb(self,db):
self.db = db

def daemon(self):
#每隔一秒查詢線程的狀態(tài),為非活動線程則設置為None
Log.log('設置守護進程')
for index,downloader in enumerate(self.downloaders):
if downloader:
if not downloader.isAlive():
Log.log('將下載器置空',index)
self.downloaders[index] = None

#檢查線程池狀態(tài)
for index,downloader in enumerate(self.downloaders):
if not downloader:
qid = self.getQID()
if qid:
#創(chuàng)建線程
t = threading.Thread(target=downloadPage,args=(qid,self.db))
self.downloaders[index] = t
t.start()
t.join()
Log.log('設置下載器',index)
#間隔一秒執(zhí)行一次
time.sleep(1)

def getQID(self):
try:
tmp = self.downloadList[0]
del self.downloadList[0]
return(tmp)
except:
return(None)

def beginDownload(self):
#創(chuàng)建守護線程
daemon = threading.Thread(target=self.daemon)
daemon.setDaemon(True)
daemon.start()
daemon.join()

def getDownloader(self):
for index,downloader in enumerate(self.downloaders):
if not downloader:
return(index)
return(None)


ADD_Q_ID = 'insert into qiushibaike(id,success) values(?,?)'
UPDATE_Q_CONTENT = 'update qiushibaike set content=? where id=?'
UPDATE_Q_STATUS = 'update qiushibaike set success=? where id=?'
Q_LIST = 'select id from qiushibaike where success=?'
Q_LIST_BY_ID = 'select count(*) from qiushibaike where id=?'
class dbConnect(object):
"""
create table qiushibaike(
id,Integer
content,Varchar
success,Interger
)
#id表示糗事的ID
#content表示糗事的內(nèi)容
#success表示是否下載成功,當該糗事內(nèi)容下載完成,且獲得上一頁、下一頁ID時表示下載完成
1表示未完成
2表示完成
"""
def __init__(self,dbpath='db.sqlite'):
self.dbpath = dbpath

def addQID(self,qid):
Log.log('插入糗事百科',qid)
#獲得連接
cn = sqlite3.connect(self.dbpath)
c = cn.cursor()

try:
#添加內(nèi)容并提交
c.execute(ADD_Q_ID,(qid,1))
cn.commit()
except:
Log.log('添加ID出錯',qid)

#關(guān)閉連接
c.close()

cn.close()
Log.log('插入成功')

def updateContent(self,qid,content):
Log.log('更新糗事百科',qid,content)
#獲得連接
cn = sqlite3.connect(self.dbpath)
c = cn.cursor()
#添加內(nèi)容并提交
c.execute(UPDATE_Q_CONTENT,(content,qid))
cn.commit()
#關(guān)閉連接
c.close()
cn.close()
Log.log('更新成功')

def updateStatus(self,qid,flag):
Log.log('更新狀態(tài)',qid,flag)
#獲得連接
cn = sqlite3.connect(self.dbpath)
c = cn.cursor()
#添加內(nèi)容并提交
c.execute(UPDATE_Q_STATUS,(flag,qid))
cn.commit()
#關(guān)閉連接
c.close()
cn.close()
Log.log('更新狀態(tài)成功')

def getList(self,unDonloaded=1):
Log.log('獲得列表')
l = []
#獲得連接
cn = sqlite3.connect(self.dbpath)
c = cn.cursor()
#獲得數(shù)據(jù)
c.execute(Q_LIST,(unDonloaded,))
rows = c.fetchall()

for i in rows:
l.append(i[0])
#關(guān)閉連接
c.close()
cn.close()

Log.log('獲得列表成功')
return(l)

class singleDownloader(object):
def __init__(self):
self.downloadList = []

def setdb(self,db):
self.db = db

def setDownloadList(self,downloadList):
self.downloadList = list(set(self.downloadList+downloadList))

def beginDownload(self):
for i in self.downloadList:
downloadPage(i,self.db)

def main():
db = dbConnect('db.sqlite')
#dp = downloaderPool()
#dp.setdb(db)
sp = singleDownloader()
sp.setdb(db)

dp=sp

unDownloadedList = db.getList()
#當還有未下載的糗事時就要繼續(xù)下載
while(len(unDownloadedList)):
#使用該列表填充下載池
dp.setDownloadList(unDownloadedList)

dp.beginDownload()

time.sleep(1)
#重置參數(shù)
unDownloadedList = db.getList()

if __name__ == '__main__':
main()


代碼是沒問題的,可以正常運行,但是希望做到以下2方面:
1、多線程下載
2、代碼分離度更高,跟面向?qū)ο?

相關(guān)文章

  • python爬蟲_微信公眾號推送信息爬取的實例

    python爬蟲_微信公眾號推送信息爬取的實例

    下面小編就為大家?guī)硪黄猵ython爬蟲_微信公眾號推送信息爬取的實例。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-10-10
  • 你眼中的Python大牛 應該都有這份書單

    你眼中的Python大牛 應該都有這份書單

    現(xiàn)在學習Python途徑很多,但是想系統(tǒng)的學習Python的知識體系,還需要靠閱讀專業(yè)的書籍來不斷積累。你眼中的Python大牛,應該都看過這些書,趕快收藏一份
    2017-10-10
  • python實現(xiàn)網(wǎng)頁錄音效果

    python實現(xiàn)網(wǎng)頁錄音效果

    這篇文章主要為大家詳細介紹了python實現(xiàn)網(wǎng)頁錄音效果,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2020-10-10
  • 基于Django框架的權(quán)限組件rbac實例講解

    基于Django框架的權(quán)限組件rbac實例講解

    今天小編就為大家分享一篇基于Django框架的權(quán)限組件rbac實例講解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-08-08
  • 基于Python繪制世界疫情地圖詳解

    基于Python繪制世界疫情地圖詳解

    這篇文章主要介紹了如何使用Python繪制世界疫情地圖,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2022-03-03
  • Python內(nèi)置函數(shù)zip map filter的使用詳解

    Python內(nèi)置函數(shù)zip map filter的使用詳解

    這篇文章主要介紹了Python內(nèi)置函數(shù)zip map filter的使用,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2021-04-04
  • Pyqt5如何讓QMessageBox按鈕顯示中文示例代碼

    Pyqt5如何讓QMessageBox按鈕顯示中文示例代碼

    這篇文章主要給大家介紹了關(guān)于Pyqt5如何讓QMessageBox按鈕顯示中文的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家學習或者使用Pyqt5具有一定的參考學習價值,需要的朋友們下面來一起學習學習吧
    2019-04-04
  • 使用Python下載抖音各大V視頻的思路詳解

    使用Python下載抖音各大V視頻的思路詳解

    這篇文章主要介紹了使用Python下載抖音各大V視頻的思路詳解,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2021-02-02
  • Python繪制散點圖的教程詳解

    Python繪制散點圖的教程詳解

    散點圖是指在回歸分析中,數(shù)據(jù)點在直角坐標系平面上的分布圖,散點圖表示因變量隨自變量而變化的大致趨勢,據(jù)此可以選擇合適的函數(shù)對數(shù)據(jù)點進行擬合。本文將用Python繪制散點圖,需要的可以參考一下
    2022-03-03
  • python代碼 FTP備份交換機配置腳本實例解析

    python代碼 FTP備份交換機配置腳本實例解析

    這篇文章主要介紹了python代碼 FTP備份交換機配置腳本實例解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2019-08-08

最新評論