爬蟲第二彈:千圖網(wǎng)電商淘寶模板圖片下載
時間:2023-06-12 18:12:02 | 來源:網(wǎng)站運營
時間:2023-06-12 18:12:02 來源:網(wǎng)站運營
爬蟲第二彈:千圖網(wǎng)電商淘寶模板圖片下載:
一、功能分析:
1、下載千圖網(wǎng)電商淘寶的所有模板圖片要求是高清版本;
2、并按照主頁面將圖片歸類文件夾。
二、思路分析:
1、利用scrapy構(gòu)建scrapy startproject qtpjt,搭建項目,并通過scrapy genspider -t basic qtspd
http://58pic.com構(gòu)建基本的爬蟲文件;
2、通過item.py構(gòu)建所有數(shù)據(jù)項;
3、setting.py將爬蟲協(xié)議關(guān)閉,打開ITEM_PIPELINES的組件
4、通過爬蟲文件qtspd.py 做到提取需要錄入數(shù)據(jù)庫所有數(shù)據(jù)項的信息;
5、通過pipelines工具對數(shù)據(jù)項進(jìn)行進(jìn)一步的處理后下載圖片到相應(yīng)文件夾;
三、具體實現(xiàn):
1、文件夾的實現(xiàn):
1.1、通過在item建立picfolder數(shù)據(jù)項,并通過在主頁面item[
"picfolder"]=response.xpath(
"//em[@class='text-green-b']/text()").extract()獲取文件夾名稱信息。
1.2、并通過以下語句構(gòu)建文件夾
folder = os.path.exists(
'C://Users//leishen//Documents//anaconda3//scrapy//master python scrapy//chapter 19//pic' +
'//' + item[
"picfolder"][0])
if not folder:
os.mkdir(
'C://Users//leishen//Documents//anaconda3//scrapy//master python scrapy//chapter 19//pic' +
'//' + item[
"picfolder"][0])
2、遍歷的實現(xiàn)
2.1主頁面遍歷
for i
in range(2,3):
#構(gòu)造出下一頁圖片列表頁的網(wǎng)址nexturl=
"http://www.58pic.com/piccate/3-0-0-default-0_2_0_0_default_0-"+str(i)+
".html"yield Request(nexturl, callback=self.parse)
2.2對圖片的鏈接的爬取:首先通過item[
"link"]=response.xpath(
"//a[@class='thumb-box']/@href").extract() 獲取每個圖片主題的子鏈接;
然后通過該鏈接,順利爬取高清模板圖片的鏈接
headers = (
"User-Agent",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.122 Safari/537.36 SE 2.X MetaSr 1.0")opener = urllib.request.build_opener()
opener.addheaders = [headers]
# 將opener安裝為全局urllib.request.install_opener(opener)
for m
in range(0, len(item[
"link"])):
data = urllib.request.urlopen(item[
"link"][m]).read()
paturl =
'<img src="(http.*?)".*?show-area-pic' item[
"picurl"] = re.compile(paturl).findall(str(data))
yield item
3、圖片的下載工作,該工作主要在pipelines.py下完成,主要利用urllib.request.urlretrieve()完成
class QtpjtPipeline(object):
def process_item(self, item, spider):
for j
in range(0, len(item[
"picurl"])):
picurl = item[
"picurl"][j]
trueurl=picurl
patlocal =
"http://pic.qiantucdn.com/58pic/.*?/.*?/.*?/(.*?).jpg" picid=re.compile(patlocal).findall(str(trueurl))[0] +
"-" + str(j)
localpath=
"C:/Users/leishen/Documents/anaconda3/scrapy/master python scrapy/chapter 19/pic/" +item[
"picfolder"][0]+
"/"+str(picid)+
".jpg" urllib.request.urlretrieve(trueurl, filename=localpath)
return item
四、項目總結(jié)
本項目主要學(xué)習(xí)兩點,1圖片的下載方法,2通過python語言自動構(gòu)建文件夾。