python爬蟲實戰(zhàn)之爬取汽車之家網(wǎng)站上的圖片

隨著生活水平的提高和快節(jié)奏生活的發(fā)展。汽車開始慢慢成為人們的必需品,瀏覽各種汽車網(wǎng)站便成為購買合適、喜歡車輛的前提。例如汽車之家網(wǎng)站中就有最新的報價和圖片以及汽車的相關內(nèi)容,是提供信息最快最全的中國汽車網(wǎng)站。本文介紹python爬蟲爬取汽車之家網(wǎng)站上的圖片的思路和具體演示代碼。

一、爬取汽車之家網(wǎng)站上的圖片思路分析
1、分析頁面,確認圖片的url是否在網(wǎng)頁源碼。
2、確認是靜態(tài)數(shù)據(jù)后,先找到總的ul標簽,在找它里面的li標簽,最后在img標簽里面的src屬性,即可獲得想要的圖片url地址。
3、通過切割圖片url的方式獲取圖片名字。
4、完成圖片命名后,使用os模塊確定圖片存放的路徑。
二、設置爬蟲代理IP
在做爬蟲的過程中,如果你爬取的頻率過快,不符合人的操作模式。有些網(wǎng)站的反爬蟲機制通過監(jiān)測到你的IP異常,訪問頻率過高。就會對你進行封IP處理。目前已有比較多的第三方平臺專門進行代理IP的服務。
三、爬取汽車之家網(wǎng)站上的圖片具體代碼
# piplines管道代碼from urllib import requestimport osclass VehicleHomePipeline:def process_item(self, item, spider):pic_url = item['pic_url']# 得到圖片名字pic_name = pic_url.split('__')[-1] # 得到xxx.jpg# os.path.dirname(__file__) 結果 D:\PycharmProjects\spider\day21\vehicle_home\vehicle_home\# 創(chuàng)建圖片存放路徑 xxx\vehicle_home\result_picpic_path = os.path.join(os.path.dirname(__file__), 'result_pic')# 下載圖片 xxx\vehicle_home\result_pic\xxx.jpgrequest.urlretrieve(pic_url, pic_path + '/' + pic_name)return item# 爬蟲代碼import scrapyfrom day21.vehicle_home.vehicle_home.items import VehicleHomeItemclass VehPicSpider(scrapy.Spider):name = 'veh_pic'allowed_domains = ['car.autohome.com.cn']base_url = 'https://car.autohome.com.cn/photolist/series/18/p{}/'start_urls = [base_url.format(1)]def parse(self, response):# 獲取圖片標簽列表pic_lists = response.xpath('//ul[@id="imgList"]/li')for pic in pic_lists:pic_url = pic.xpath('./a/img/@src').extract_first()# 上述獲取的url需要進一步補全pic_url = response.urljoin(pic_url)item = VehicleHomeItem()item['pic_url'] = pic_urlprint(item)yield item# 翻頁邏輯for page in range(2, 3):next_url = self.base_url.format(page)yield scrapy.Request(next_url)
以上就是python爬蟲爬取汽車之家網(wǎng)站上的圖片的思路和具體演示代碼,大家可以套用代碼靈活使用喲~
*聲明:本文于網(wǎng)絡整理,版權歸原作者所有,如來源信息有誤或侵犯權益,請聯(lián)系我們刪除或授權

評論
圖片
表情
