啥也不说直接上代码[Python] 纯文本查看 复制代码 import requests
import threading
from lxml import etree
from urllib import request
import os
import re
from queue import Queue
class Produce(threading.Thread):
headers = {
'User-Agent': 'Mozilla/5.0'
}
i = 1
def __init__(self, page_queue, img_queue, *args, **kwargs):
super(Produce, self).__init__(*args, **kwargs)
self.page_queue = page_queue
self.img_queue = img_queue
def run(self):
while True:
if self.page_queue.empty():
break
url = self.page_queue.get()
self.parse_page(url)
def parse_page(self, url):
r = requests.get(url, self.headers)
r.encoding = r.apparent_encoding
html = etree.HTML(r.text)
imgs = html.xpath('//div[@class="random_article"]//img[@class!="gif"]')
for img in imgs:
# img_url = img.xpath('@data-original') 或者
img_url = img.get('data-original')
name = img.get('alt')
name = re.sub(r'\??。\.', "", name)
if name:
name = img.get('alt')
else:
name = self.i
self.i += 1
suddix = os.path.splitext(img_url)[1]
filename = str(name) + suddix
self.img_queue.put((img_url, filename))
class Consumer(threading.Thread):
def __init__(self, page_queue, img_queue, *args, **kwargs):
super(Consumer, self).__init__(*args, **kwargs)
self.page_queue = page_queue
self.img_queue = img_queue
def run(self):
while True:
if self.img_queue.empty() and self.page_queue.empty():
return
img_url, filename = self.img_queue.get()
request.urlretrieve(img_url, 'image/' + filename)
print(filename+'下载完成')
def main():
page_queue = Queue(500)
img_queue = Queue(1000)
for x in range(1,10):
url = 'https://www.doutula.com/article/list/?page={}'.format(x)
page_queue.put(url)
for x in range(5):
t = Produce(page_queue, img_queue)
t.start()
for x in range(5):
t = Consumer(page_queue, img_queue)
t.start()
if __name__ == '__main__':
main()
顺便在这里问一下各位大佬
for x in range(1,10):url = 'https://www.doutula.com/article/list/?page={}'.format(x)
page_queue.put(url)
这段代码如果改成for x in range(1,5),就会不进行爬取,直接结束??也不知道是啥原因 |