美文网首页
python多线程爬取斗图网表情包

python多线程爬取斗图网表情包

作者: 小黑_328a | 来源:发表于2020-01-29 10:20 被阅读0次

一共需要导入如下的库

from bs4 import BeautifulSoup
import requests
import time
import threading
import queue

网址是https://www.doutula.com/photo/list/?page=1

首先要这是request头。

调用request.get获取相应,

将源代码写入到‘1.html’

url='https://www.doutula.com/photo/list/?page=1'

headers={'user-agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36'}

resp=requests.get(url,headers=headers)
with open('1.html','bw') as fp:
    fp.write(resp.content)

使用beautiful解析html文本,设置lxml解析器。

接下来是多线程爬取动图。

python的多线程 使用于IO繁忙型,不适用于cpu计算型。

因为python的多线程是单核多线程。无法并行,只能并发。

python自带的队列queue具有原子性,是线程安全的。但仍需要引入锁来控制。

引入time库是为了计算程序运行时间.


with open('1.html','r',encoding='utf-8') as fp:
    html=fp.read()

text=BeautifulSoup(html,'lxml')
div=text.select_one('div.page-content')
imgs=div.find_all('img')
i=0
start=time.time()
#--------------------------------------------------------------------------

def go():
    global Q,i

    while True:
        Lock.acquire()
        if(Q.empty()):
            Lock.release()
            break
        url=Q.get()
        Lock.release()
        resp = requests.get(url, headers=headers)
        Lock.acquire()
        with open('img/' + str(i) + '.jpg', 'bw') as fp:
            i += 1
            Lock.release()
            fp.write(resp.content)

Q=queue.Queue(90)
i=0
for img in imgs:
    if (img.get('data-backup')):
        img_url = img['data-backup']

        Q.put(img_url)
Lock=threading.RLock()
T=[]
for cnt in range(5):
    t=threading.Thread(target=go)
    T.append(t)
    t.start()

for t in T:
    t.join()
end=time.time()
print('执行时间:',end-start,'秒')

相关文章

网友评论

      本文标题:python多线程爬取斗图网表情包

      本文链接:https://www.haomeiwen.com/subject/lisvthtx.html