一.用多线程写的爬书站
准备用多进程改下
import threading
import requests,os,time,random
from lxml import html
from urllib import parse
#创建Lock()给数组加锁
gLock = threading.Lock()
#公用数组,记录章节下载链接
book_link_lst = []
#公用字典保存book信息
#key:'book_name','index_link','book_path','book_files','thread_isover','code'
book_info = dict()
#创建一个头列表
user_agent_list = ["Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; …) Gecko/20100101 Firefox/61.0",
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36",
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.62 Safari/537.36",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36",
"Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)",
"Mozilla/5.0 (Macintosh; U; PPC Mac OS X 10.5; en-US; rv:1.9.2.15) Gecko/20110303 Firefox/3.6.15",
]
headers={'User-Agent':random.choice(user_agent_list)}
#获取html文件
def get_html(url):
code = book_info['code']
headers={'User-Agent':random.choice(user_agent_list)}
page = requests.get(url,headers).content.decode(code)
strhtml = html.fromstring(page)
return strhtml
#获取章节链接返回数组[[index,连接],]
def get_booklist(strhtml):
rlst = list()
#书名写入公用字典
book_info['book_name'] = strhtml.xpath('//*[@id="info"]/h1/text()')[0]
listurls = [parse.urljoin(book_info['index_link'],i) for i in strhtml.xpath('//*[@id="list"]/dl/dd/a/@href')]
return list(zip(range(len(listurls)),listurls))
#起始函数,获取章节链接,放入公用数组
def crate_link(url,code):
#页面编码写入公用字典
book_info['code'] = code
#链接写入公用字典
book_info['index_link'] = url
#初始化结束链接数
book_info['thread_isover'] = 0
#获得索引页页面文件
page = get_html(url)
#获得章节列表
book_links = get_booklist(page)
for b in book_links:
#章节列表追加入公用列表
book_link_lst.append(b)
#文件合并
def merge_file():
#获得文件路径
tmpfiledir = book_info['book_path']
#获得文件列表 路径+文件名 os.listdir()获得目录下的所有文件名
tmpnameList = [tmpfiledir+'/'+i for i in os.listdir(tmpfiledir)]
#文件列表写入公用字典
book_info['book_files'] = tmpnameList
#文件排序
tmpnameList.sort()
#获得文件名
tmpbookname = book_info['book_name']
#创建合并文件
tmpbookfile = open('book/{}.txt'.format(tmpbookname),'a',encoding = 'utf-8')
#打开文件列表,并读取文件到新文件
for i in tmpnameList:
x = open(i,'r',encoding = 'utf-8')
tmpbookfile.write(x.read())
x.close()
tmpbookfile.close()
#创建多线程
class Down_books(threading.Thread):
#下载章节内容并保存在文件夹里
def run(self):
doit = True
while doit:
#加锁
gLock.acquire()
if len(book_link_lst) == 0:
gLock.release()
continue
else:
#获得链接字符串和编号 (index,url)
tmpindex,tmpurl = book_link_lst.pop()
#解锁
gLock.release()
#获得章节页面
nhtml = get_html(tmpurl)
#获得章节名称
nname = nhtml.xpath('//*[@class="bookname"]/h1/text()')[0].replace('?','')
#获得章节内容
ncont = nhtml.xpath('//*[@id="content"]/text()')
#生成保存目录
book_info['book_path'] = 'books\\{}'.format(book_info['book_name'])
#查询目录是否存在,否则创建书名的目录
if not os.path.exists(book_info['book_path']):
os.makedirs(book_info['book_path'])
#生成文件名
tmpfilename = '0'*(5-len(str(tmpindex)))+str(tmpindex)+nname
#保存章节内容到文件
with open('books\\{}\\{}.txt'.format(book_info['book_name'],tmpfilename),'w',encoding="utf-8") as b:
b.write(nname+'\n')
for c in ncont:
c = c.replace('<!--go-->','')
c = c.replace('<!--over-->','')
b.write(c+'\n')
print('下载完成:'+nname)
#如果待下载链接列表空了,就结束这个循环,完结这个线程
if len(book_link_lst) == 0:
book_info['thread_isover'] += 1
print('线程结束')
#结束循环
doit = False
#启动线程前的准备工作
crate_link('https://www.23txt.com/files/article/html/65/65662/','gbk')
#启动线程 10个
for x in range(5):
Down_books().start()
#循环查询待下载列表是否为空,如为空则开始合并文章
Down_doing = True
while Down_doing:
if book_info['thread_isover'] == 5:
merge_file()
Down_doing = False
isdel = input('文件已合并,是否删除各章节文件?y/n:')
if isdel == 'y':
for i in book_info['book_files']:
os.remove(i)
print('文件删除完毕')
print()
else:
time.sleep(10)
二.改写多进程
看了一个关于Pool操作的说明
# -*- coding: utf-8 -*-
import time
from multiprocessing import Pool
def run(fn):
#fn: 函数参数是数据列表的一个元素
time.sleep(1)
print(fn*fn)
if __name__ == "__main__":
testFL = [1,2,3,4,5,6]
print ('shunxu:') #顺序执行(也就是串行执行,单进程)
s = time.time()
for fn in testFL:
run(fn)
t1 = time.time()
print ("顺序执行时间:", int(t1 - s))
print ('concurrent:') #创建多个进程,并行执行
pool = Pool(10) #创建拥有10个进程数量的进程池
#testFL:要处理的数据列表,run:处理testFL列表中数据的函数
pool.map(run, testFL)
pool.close()#关闭进程池,不再接受新的进程
pool.join()#主进程阻塞等待子进程的退出
t2 = time.time()
print ("并行执行时间:", int(t2-t1))
准备根据这个流程把爬书站的多线程程序改写成多进程
查询和测试了下,发现多进程和多线程相比有很大的不同。多线程可以使用主线程中的函数和变量,多进程就不行了,多进程相互之间是独立的,没有任何联系,守护进程还没看,看了再说。
所以需要将在多进程中使用的公共变量和函数都做下处理,函数并入多进程函数中,放弃变量。
1.添加引用模块
from multiprocessing import Pool
2.改写多线程任务为多进程任务
多线程代码:
#创建多线程
class Down_books(threading.Thread):
#下载章节内容并保存在文件夹里
def run(self):
doit = True
while doit:
#加锁
gLock.acquire()
if len(book_link_lst) == 0:
gLock.release()
continue
else:
#获得链接字符串和编号 (index,url)
tmpindex,tmpurl = book_link_lst.pop()
#解锁
gLock.release()
#获得章节页面
nhtml = get_html(tmpurl)
#获得章节名称
nname = nhtml.xpath('//*[@class="bookname"]/h1/text()')[0].replace('?','')
#获得章节内容
ncont = nhtml.xpath('//*[@id="content"]/text()')
#生成保存目录
book_info['book_path'] = 'books\\{}'.format(book_info['book_name'])
#查询目录是否存在,否则创建书名的目录
if not os.path.exists(book_info['book_path']):
os.makedirs(book_info['book_path'])
#生成文件名
tmpfilename = '0'*(5-len(str(tmpindex)))+str(tmpindex)+nname
#保存章节内容到文件
with open('books\\{}\\{}.txt'.format(book_info['book_name'],tmpfilename),'w',encoding="utf-8") as b:
b.write(nname+'\n')
for c in ncont:
c = c.replace('<!--go-->','')
c = c.replace('<!--over-->','')
b.write(c+'\n')
print('下载完成:'+nname)
#如果待下载链接列表空了,就结束这个循环,完结这个线程
if len(book_link_lst) == 0:
book_info['thread_isover'] += 1
print('线程结束')
#结束循环
doit = False
多线程任务是声明了一个threading.Thread类,并实例化了多个来同时进行。多进程无法使用里面用到的变量和函数调用。所以需要改写一下。
首先,去掉类的声明语句,把里面的函数拿出来,并将里面的代码块的缩进位向移动一位。
#创建多线程
class Down_books(threading.Thread):
循环去掉,加锁去掉,是否结束循环的判断语句去掉。别忘了再将剩余代码缩进向前移动。
doit = True
while doit:
#加锁
gLock.acquire()
if len(book_link_lst) == 0:
gLock.release()
continue
else:
通过读取变量book_link_lst来读取任务数据的语句也需要改。
#获得链接字符串和编号 (index,url)
tmpindex,tmpurl = book_link_lst.pop()
不过暂时先记着,一会儿把这个变量作为参数传进来。
解锁去掉
#解锁
gLock.release()
#获得章节页面
下面是调用其他函数的部分,
nhtml = get_html(tmpurl)
把get_html()函数中的内容拿过来,替换这个语句。还是别忘记调整缩进
#获得章节页面
code = book_info['code']
headers={'User-Agent':random.choice(user_agent_list)}
page = requests.get(url,headers).content.decode(code)
nhtml = html.fromstring(page)
替换过了,但里面还有一个变量,是记录的当前页面编码,使用的是’gbk’还是’utf-8’。
page = requests.get(url,headers).content.decode('utf-8')
这个暂时还没有什么好办法,先写死吧,根据实际情况再调整吧。做过测试,使用try进行判断,结果还是会跳出,回来再想想其他办法。
headers选一个写死!没法用变量来随便换了。
headers={'User-Agent':"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.62 Safari/537.36"}
这些改过后,就变成了了:
#获得章节页面
headers={'User-Agent':"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.62 Safari/537.36"}
page = requests.get(url,headers).content.decode('utf-8')
nhtml = html.fromstring(page)
#获得章节名称
nname = nhtml.xpath('//*[@class="bookname"]/h1/text()')[0].replace('?','')
#获得章节内容
ncont = nhtml.xpath('//*[@id="content"]/text()')
下面是文件操作的部分,
#生成保存目录
book_info['book_path'] = 'books\\{}'.format(book_info['book_name'])
#查询目录是否存在,否则创建书名的目录
if not os.path.exists(book_info['book_path']):
os.makedirs(book_info['book_path'])
首先,这一段我们不放在多进程里,单独拿出来,放在多进程之前的准备工作里。总不能每个进程都检查一遍目录吧。现在放在起始函数里的内容就是:
#起始函数,获取章节链接,放入公用数组
def crate_link(url,code):
#页面编码写入公用字典
book_info['code'] = code
#链接写入公用字典
book_info['index_link'] = url
#初始化结束链接数
book_info['thread_isover'] = 0
#获得索引页页面文件
page = get_html(url)
#获得章节列表
book_links = get_booklist(page)
for b in book_links:
#章节列表追加入公用列表
book_link_lst.append(b)
#生成保存目录
book_info['book_path'] = 'books\\{}'.format(book_info['book_name'])
#查询目录是否存在,否则创建书名的目录
if not os.path.exists(book_info['book_path']):
os.makedirs(book_info['book_path'])
那多进程里面剩余的代码就是:
#生成文件名
tmpfilename = '0'*(5-len(str(tmpindex)))+str(tmpindex)+nname
#保存章节内容到文件
with open('books\\{}\\{}.txt'.format(book_info['book_name'],tmpfilename),'w',encoding="utf-8") as b:
b.write(nname+'\n')
for c in ncont:
c = c.replace('<!--go-->','')
c = c.replace('<!--over-->','')
b.write(c+'\n')
print('下载完成:'+nname)
#如果待下载链接列表空了,就结束这个循环,完结这个线程
if len(book_link_lst) == 0:
book_info['thread_isover'] += 1
print('线程结束')
#结束循环
doit = False
看,这里面还用到了变量book_info[‘book_name’],书名。
书名怎么得到?我们再多线程里是从书的详情页里得到书名,然后保存在变量里。现在需要在章节页面里找到书名,并获取。
书名在这里,获取xpath
书名在一个div里的一串a标签的最后一个。那就这样……
#获得书名
nbookname = nhtml.xpath('//div[@class="con_top"]/a/text()')[-1]
然后替换book_info[‘book_name’]
with open('books\\{}\\{}.txt'.format(nbookname,tmpfilename),'w',encoding="utf-8") as b:
顺便把最下面多余的地方删掉
print('下载完成:'+nname)
#如果待下载链接列表空了,就结束这个循环,完结这个线程
if len(book_link_lst) == 0:
book_info['thread_isover'] += 1
print('线程结束')
#结束循环
doit = False
由于多进程执行时,我们会先暂停主进程的执行,所以print()就用不成了。并且计数器和结束判断任务列表是否为空的语句也用不上了。就统统删除。
最后,我们把刚才的参数改下,函数开头的book_link_lst.pop()改成传入参数。
好了,现在我们多进程函数里就成了这样了:
#下载章节内容并保存在文件夹里
def Down_books(url):
#获得链接字符串和编号 (index,url)
tmpindex,tmpurl = url
#获得章节页面
headers={'User-Agent':"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.62 Safari/537.36"}
page = requests.get(tmpurl ,headers).content.decode('utf-8')
nhtml = html.fromstring(page)
#获得章节名称
nname = nhtml.xpath('//*[@class="bookname"]/h1/text()')[0].replace('?','')
#获得章节内容
ncont = nhtml.xpath('//*[@id="content"]/text()')
#获得书名
nbookname = nhtml.xpath('//div[@class="con_top"]/a/text()')[-1]
#生成文件名
tmpfilename = '0'*(5-len(str(tmpindex)))+str(tmpindex)+nname
#保存章节内容到文件
with open('books\\{}\\{}.txt'.format(nbookname,tmpfilename),'w',encoding="utf-8") as b:
b.write(nname+'\n')
for c in ncont:
c = c.replace('<!--go-->','')
c = c.replace('<!--over-->','')
b.write(c+'\n')
最后,把运行流程屡一下,现在剩下还没改的语句是:
#启动线程前的准备工作
crate_link('https://www.23txt.com/files/article/html/65/65662/','gbk')
#启动线程 10个
for x in range(5):
Down_books().start()
#循环查询待下载列表是否为空,如为空则开始合并文章
Down_doing = True
while Down_doing:
if book_info['thread_isover'] == 5:
merge_file()
Down_doing = False
isdel = input('文件已合并,是否删除各章节文件?y/n:')
if isdel == 'y':
for i in book_info['book_files']:
os.remove(i)
print('文件删除完毕')
print()
else:
time.sleep(10)
咱们回过头来看下多进程的执行流程,从找到的多进程的代码里摘过来:
t1 = time.time()
print ('concurrent:') #创建多个进程,并行执行
pool = Pool(10) #创建拥有10个进程数量的进程池
#testFL:要处理的数据列表,run:处理testFL列表中数据的函数
pool.map(run, testFL)
pool.close()#关闭进程池,不再接受新的进程
pool.join()#主进程阻塞等待子进程的退出
t2 = time.time()
print ("并行执行时间:", int(t2-t1))
根据这个改一下,主要是这一句
pool.map(Down_books, testFL)
改成
pool.map(Down_books, book_link_lst)
好了,现在我们就变成了:
#启动线程前的准备工作
crate_link('https://www.23txt.com/files/article/html/65/65662/','gbk')
t1 = time.time()
print ('concurrent:') #创建多个进程,并行执行
pool = Pool(10) #创建拥有10个进程数量的进程池
#book_link_lst:要处理的数据列表,Down_books:处理book_link_lst列表中数据的函数
pool.map(Down_books, book_link_lst)
pool.close()#关闭进程池,不再接受新的进程
pool.join()#主进程阻塞等待子进程的退出
t2 = time.time()
print ("并行执行时间:", int(t2-t1))
再把这些个操作封装到一个函数里:
def runc(url,code):
crate_link(Down_books,code)
t1 = time.time()
print ('concurrent:') #创建多个进程,并行执行
pool = Pool(10) #创建拥有10个进程数量的进程池
#book_link_lst:要处理的数据列表,Down_books:处理book_link_lst列表中数据的函数
pool.map(Down_books, book_link_lst)
pool.close()#关闭进程池,不再接受新的进程
pool.join()#主进程阻塞等待子进程的退出
t2 = time.time()
print ("并行执行时间:", int(t2-t1))
下载后的合并操作加到最后,顺便选择是否删除下载的分章节:
def runc(url,code):
crate_link(url,code)
t1 = time.time()
print ('concurrent:') #创建多个进程,并行执行
pool = Pool(10) #创建拥有10个进程数量的进程池
#book_link_lst:要处理的数据列表,Down_books:处理book_link_lst列表中数据的函数
pool.map(Down_books, book_link_lst)
pool.close()#关闭进程池,不再接受新的进程
pool.join()#主进程阻塞等待子进程的退出
t2 = time.time()
print ("并行执行时间:", int(t2-t1))
print('正在合并文件……')
merge_file()
isdel = input('文件已合并,是否删除各章节文件?y/n:')
if isdel == 'y':
for i in book_info['book_files']:
os.remove(i)
os.rmdir(book_info['book_path'])
print('文件删除完毕')
最后再加上调试语句:
if __name__ == "__main__":
runc('https://www.23txt.com/files/article/html/65/65662/','gbk')
试一下,这里放上完整代码:
import time
from multiprocessing import Pool
import threading
import requests,os,time,random
from lxml import html
from urllib import parse
#创建Lock()给数组加锁
gLock = threading.Lock()
#公用数组,记录章节下载链接
book_link_lst = []
#公用字典保存book信息
#key:'book_name','index_link','book_path','book_files','thread_isover','code'
book_info = dict()
#创建一个头列表
user_agent_list = ["Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; …) Gecko/20100101 Firefox/61.0",
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36",
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.62 Safari/537.36",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36",
"Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)",
"Mozilla/5.0 (Macintosh; U; PPC Mac OS X 10.5; en-US; rv:1.9.2.15) Gecko/20110303 Firefox/3.6.15",
]
headers={'User-Agent':random.choice(user_agent_list)}
#获取html文件
def get_html(url):
code = book_info['code']
headers={'User-Agent':random.choice(user_agent_list)}
page = requests.get(url,headers).content.decode(code)
strhtml = html.fromstring(page)
return strhtml
#获取章节链接返回数组[[index,连接],]
def get_booklist(strhtml):
rlst = list()
#书名写入公用字典
book_info['book_name'] = strhtml.xpath('//*[@id="info"]/h1/text()')[0]
listurls = [parse.urljoin(book_info['index_link'],i) for i in strhtml.xpath('//*[@id="list"]/dl/dd/a/@href')]
return list(zip(range(len(listurls)),listurls))
#起始函数,获取章节链接,放入公用数组
def crate_link(url,code):
#页面编码写入公用字典
book_info['code'] = code
#链接写入公用字典
book_info['index_link'] = url
#初始化结束链接数
book_info['thread_isover'] = 0
#获得索引页页面文件
page = get_html(url)
#获得章节列表
book_links = get_booklist(page)
for b in book_links:
#章节列表追加入公用列表
book_link_lst.append(b)
#生成保存目录
book_info['book_path'] = 'books\\{}'.format(book_info['book_name'])
#查询目录是否存在,否则创建书名的目录
if not os.path.exists(book_info['book_path']):
os.makedirs(book_info['book_path'])
#文件合并
def merge_file():
#获得文件路径
tmpfiledir = book_info['book_path']
#获得文件列表 路径+文件名 os.listdir()获得目录下的所有文件名
tmpnameList = [tmpfiledir+'/'+i for i in os.listdir(tmpfiledir)]
#文件列表写入公用字典
book_info['book_files'] = tmpnameList
#文件排序
tmpnameList.sort()
#获得文件名
tmpbookname = book_info['book_name']
#创建合并文件
tmpbookfile = open('book/{}.txt'.format(tmpbookname),'a',encoding = 'utf-8')
#打开文件列表,并读取文件到新文件
for i in tmpnameList:
x = open(i,'r',encoding = 'utf-8')
tmpbookfile.write(x.read())
x.close()
tmpbookfile.close()
#下载章节内容并保存在文件夹里
def Down_books(url):
#获得链接字符串和编号 (index,url)
tmpindex,tmpurl = url
#获得章节页面
headers={'User-Agent':"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.62 Safari/537.36"}
page = requests.get(tmpurl,headers).content.decode('gbk')
strhtml = html.fromstring(page)
nhtml = strhtml
#获得章节名称
nname = nhtml.xpath('//*[@class="bookname"]/h1/text()')[0].replace('?','')
#获得章节内容
ncont = nhtml.xpath('//*[@id="content"]/text()')
#获得书名
nbookname = nhtml.xpath('//div[@class="con_top"]/a/text()')[-1]
#生成文件名
tmpfilename = '0'*(5-len(str(tmpindex)))+str(tmpindex)+nname
#保存章节内容到文件
with open('books\\{}\\{}.txt'.format(nbookname,tmpfilename),'w',encoding="utf-8") as b:
b.write(nname+'\n')
for c in ncont:
c = c.replace('<!--go-->','')
c = c.replace('<!--over-->','')
b.write(c+'\n')
def runc(url,code):
t1 = time.time()
crate_link(url,code)
print ('concurrent:') #创建多个进程,并行执行
pool = Pool(10) #创建拥有10个进程数量的进程池
#book_link_lst:要处理的数据列表,Down_books:处理book_link_lst列表中数据的函数
pool.map(Down_books, book_link_lst)
pool.close()#关闭进程池,不再接受新的进程
pool.join()#主进程阻塞等待子进程的退出
t2 = time.time()
print ("并行执行时间:", int(t2-t1))
print('正在合并文件……')
merge_file()
isdel = input('文件已合并,是否删除各章节文件?y/n:')
if isdel == 'y':
for i in book_info['book_files']:
os.remove(i)
os.rmdir(book_info['book_path'])
print('文件删除完毕')
if __name__ == "__main__":
runc('https://www.23txt.com/files/article/html/65/65662/','gbk')