Python實現(xiàn)從訂閱源下載圖片的方法
更新時間:2015年03月11日 09:38:54 作者:saintatgod
這篇文章主要介紹了Python實現(xiàn)從訂閱源下載圖片的方法,涉及Python采集的技巧,具有一定參考借鑒價值,需要的朋友可以參考下
本文實例講述了Python實現(xiàn)從訂閱源下載圖片的方法。分享給大家供大家參考。具體如下:
這段代碼是基于python 3.4實現(xiàn)的,和python2.X 比起來有了好多差別啊。
這是一個練習,數(shù)據(jù)源來自網(wǎng)易訂閱。代碼如下:
復制代碼 代碼如下:
__author__ = 'Saint'
import os
import urllib.request
import json
from html.parser import HTMLParser
# 從獲取的網(wǎng)頁內容篩選圖片的內容
class MyHtmlParser(HTMLParser):
links = []
def handle_starttag(self, tag, attrs):
if tag == "img":
if len(attrs) == 0:
pass
else:
for name, value in attrs:
if name == "src":
self.links.append(value)
class Down(object):
# 總的目錄
img_path = "E:/saint"
# 下載目錄
dir = ''
# 采集源地址
collect_links = ["http://dy.163.com/v2/media/articlelist/T1374483113516-1", "http://dy.163.com/v2/media/articlelist/T1420776257254-1", "http://dy.163.com/v2/media/articlelist/T1376641060407-1"]
img_links = "http://dy.163.com/v2/article"
def handleCollect(self):
for collect_link in self.collect_links:
notice = "開始從[" + collect_link + "]采集圖片"
print(notice)
# 建立下載的目錄
dir_name = collect_link.split("/")[-1]
self.isDirExists(dir_name)
dict = self.getListFromSubscribe(collect_link)
if dict == False:
print("數(shù)據(jù)采集失敗,是否繼續(xù)(y/n)")
op = input();
if op == "y":
os.system("cls")
pass
elif op == "n":
print("停止采集")
break
else:
os.system("cls")
print("非法輸入")
break
else:
for page in dict:
page_uri = self.img_links + "/" + page["tid"] + "/" + page["docid"]
self.getImgFromUri(page_uri)
print("是否繼續(xù)(y/n)")
new_op = input();
if new_op == "n":
os.system("cls")
print("采集完畢")
break
print("OK")
# 從訂閱源獲取目錄
def getListFromSubscribe(self, uri):
res = urllib.request.urlopen(uri)
if res.code < 200 or res.code > 300:
os.system("clear")
return False
else:
result = res.read().decode("gbk") # 3.4版本的read()返回的是byte類型,需要decode()處理,選項是網(wǎng)頁編碼
dict = json.loads(result)
if dict['code'] != 1:
print(dict['msg'])
return False
else:
return dict['data']
# 獲取本期訂閱的網(wǎng)頁,并從網(wǎng)頁中提取出來需要的圖片
def getImgFromUri(self, uri):
html_code = urllib.request.urlopen(uri).read().decode("gbk")
hp = MyHtmlParser()
hp.feed(html_code)
hp.close()
for link in hp.links: # hp.links 是圖片的下載地址的列表
self.writeToDisk(link)
# 檢查文件目錄是否存在,如果不存在,則創(chuàng)建目錄
def isDirExists(self, dir_name):
self.dir = self.img_path + dir_name
isExists = os.path.exists(self.dir)
if not isExists:
os.makedirs(self.dir)
return True
else:
return True
# 下載文件,并且寫入磁盤
def writeToDisk(self, url):
os.chdir(self.dir)
file = urllib.request.urlopen(url).read()
file_name = url.split("/")[-1]
open(file_name, "wb").write(file)
return True
if __name__ == "__main__":
down = Down()
down.handleCollect()
import os
import urllib.request
import json
from html.parser import HTMLParser
# 從獲取的網(wǎng)頁內容篩選圖片的內容
class MyHtmlParser(HTMLParser):
links = []
def handle_starttag(self, tag, attrs):
if tag == "img":
if len(attrs) == 0:
pass
else:
for name, value in attrs:
if name == "src":
self.links.append(value)
class Down(object):
# 總的目錄
img_path = "E:/saint"
# 下載目錄
dir = ''
# 采集源地址
collect_links = ["http://dy.163.com/v2/media/articlelist/T1374483113516-1", "http://dy.163.com/v2/media/articlelist/T1420776257254-1", "http://dy.163.com/v2/media/articlelist/T1376641060407-1"]
img_links = "http://dy.163.com/v2/article"
def handleCollect(self):
for collect_link in self.collect_links:
notice = "開始從[" + collect_link + "]采集圖片"
print(notice)
# 建立下載的目錄
dir_name = collect_link.split("/")[-1]
self.isDirExists(dir_name)
dict = self.getListFromSubscribe(collect_link)
if dict == False:
print("數(shù)據(jù)采集失敗,是否繼續(xù)(y/n)")
op = input();
if op == "y":
os.system("cls")
pass
elif op == "n":
print("停止采集")
break
else:
os.system("cls")
print("非法輸入")
break
else:
for page in dict:
page_uri = self.img_links + "/" + page["tid"] + "/" + page["docid"]
self.getImgFromUri(page_uri)
print("是否繼續(xù)(y/n)")
new_op = input();
if new_op == "n":
os.system("cls")
print("采集完畢")
break
print("OK")
# 從訂閱源獲取目錄
def getListFromSubscribe(self, uri):
res = urllib.request.urlopen(uri)
if res.code < 200 or res.code > 300:
os.system("clear")
return False
else:
result = res.read().decode("gbk") # 3.4版本的read()返回的是byte類型,需要decode()處理,選項是網(wǎng)頁編碼
dict = json.loads(result)
if dict['code'] != 1:
print(dict['msg'])
return False
else:
return dict['data']
# 獲取本期訂閱的網(wǎng)頁,并從網(wǎng)頁中提取出來需要的圖片
def getImgFromUri(self, uri):
html_code = urllib.request.urlopen(uri).read().decode("gbk")
hp = MyHtmlParser()
hp.feed(html_code)
hp.close()
for link in hp.links: # hp.links 是圖片的下載地址的列表
self.writeToDisk(link)
# 檢查文件目錄是否存在,如果不存在,則創(chuàng)建目錄
def isDirExists(self, dir_name):
self.dir = self.img_path + dir_name
isExists = os.path.exists(self.dir)
if not isExists:
os.makedirs(self.dir)
return True
else:
return True
# 下載文件,并且寫入磁盤
def writeToDisk(self, url):
os.chdir(self.dir)
file = urllib.request.urlopen(url).read()
file_name = url.split("/")[-1]
open(file_name, "wb").write(file)
return True
if __name__ == "__main__":
down = Down()
down.handleCollect()
希望本文所述對大家的Python程序設計有所幫助。
您可能感興趣的文章:
- python批量下載圖片的三種方法
- python下載圖片實現(xiàn)方法(超簡單)
- Python實現(xiàn)批量下載圖片的方法
- Python爬蟲實現(xiàn)抓取京東店鋪信息及下載圖片功能示例
- 詳解Python下載圖片并保存本地的兩種方式
- Python常用模塊之requests模塊用法分析
- 用python的requests第三方模塊抓取王者榮耀所有英雄的皮膚實例
- python3使用requests模塊爬取頁面內容的實戰(zhàn)演練
- Python 使用requests模塊發(fā)送GET和POST請求的實現(xiàn)代碼
- Python使用lxml模塊和Requests模塊抓取HTML頁面的教程
- python中requests模塊的使用方法
- Python實現(xiàn)使用request模塊下載圖片demo示例
相關文章
Python Matplotlib 實現(xiàn)3D繪圖詳解
Matplotlib在二維繪圖的基礎上,構建了一部分較為實用的3D繪圖程序包。本文將為大家詳細介紹通過調用該程序包接口繪制 3D散點圖、3D曲面圖、3D線框圖。感興趣的同學可以了解一下2021-11-11python自動化測試selenium核心技術三種等待方式詳解
這篇文章主要為大家介紹了python自動化測試selenium的核心技術三種等待方式示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步早日升職加薪2021-11-11python獲取全國最新省市區(qū)數(shù)據(jù)并存入表實例代碼
我們在開發(fā)中經(jīng)常會遇到獲取省市區(qū)等信息的時候,下面這篇這篇文章主要給大家介紹了關于python獲取全國最新省市區(qū)數(shù)據(jù)并存入表的相關資料,需要的朋友可以參考下2021-08-08