下载糗事百科的内容_python版
2020-02-23 04:41:59
供稿:网友
代码如下:
#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):
#获得根节点
self.html = xml.dom.minidom.parseString(content)
def parse(self):
Log.log('开始提取数据')
contents = {'content':'','url':[]}
#获得div节点
divs = self.html.getElementsByTagName('div')
#获得content节点
for div in divs:
if div.hasAttribute('class') and /
div.getAttribute('class') == 'content':
#获得糗事百科的内容
textNode = div.childNodes[0]
qContent = textNode.data
#数据填充
contents['content'] = qContent
#获得上一糗事、下一糗事节点
spans = self.html.getElementsByTagName('span')
for span in spans:
pspan = span.parentNode
if pspan.tagName == 'a':
#pspan为对应的链接,此时需要将对应的地址加入数据库
url = pspan.getAttribute('href')
qid = url[10:][:-4]
#数据填充
contents['url'].append(qid)
Log.log('提取数据完毕')
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)
#下载池,表示同时允许下载的链接个数
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):
#每隔一秒查询线程的状态,为非活动线程则设置为None
Log.log('设置守护进程')
for index,downloader in enumerate(self.downloaders):
if downloader:
if not downloader.isAlive():
Log.log('将下载器置空',index)
self.downloaders[index] = None
#检查线程池状态
for index,downloader in enumerate(self.downloaders):
if not downloader:
qid = self.getQID()
if qid:
#创建线程
t = threading.Thread(target=downloadPage,args=(qid,self.db))
self.downloaders[index] = t
t.start()
t.join()