Python利用gevent協程和xpath正則表達式來爬取某一網站的圖片

爬蟲爬取某一網站的圖片,看其效果 

import urllib.request
import gevent,time
from gevent import monkey
from lxml import etree


monkey.patch_all() #替換,將普通模塊中的方法換爲gevent中的方法
res = urllib.request.urlopen('https://www.tupianzj.com/meinv/mm/')
txt = res.read() #將html格式的網頁賦值爲txt
html = etree.HTML(str(txt))  #etree.HTML()方法只能分析字符串,即String
lis = html.xpath("//div[@id='container']//li//img/@src")   #選擇img標籤中的src屬性

def work(x):
    #img_connection = urllib.request.urlopen("https://img.tupianzj.com/uploads/200514/9-200514094339638.jpg")
    #for i in range():
    img_connection = urllib.request.urlopen(lis[x])  #協程,按序打開列表中的網頁
    fd = open('%d.jpg'% x,'wb')
    fd.write(img_connection.read())
    fd.close()

#img_fd = img_connection.read()

list2 = list()
for x in range(33):
    g1 = gevent.spawn(work,x) #spawn即生成函數,帶入方法,方法中的參數
    list2.append(g1)

gevent.joinall(list2)  #joinall(),回收列表中的協程


運行效果: 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章