使用Python3編寫抓取網(wǎng)頁和只抓網(wǎng)頁圖片的腳本
更新時間:2015年08月20日 09:46:01 作者:damotiansheng
這篇文章主要介紹了使用Python3編寫抓取網(wǎng)頁和只抓網(wǎng)頁圖片的腳本,使用到了urllib模塊,需要的朋友可以參考下
最基本的抓取網(wǎng)頁內(nèi)容的代碼實現(xiàn):
#!/usr/bin/env python from urllib import urlretrieve def firstNonBlank(lines): for eachLine in lines: if not eachLine.strip(): continue else: return eachLine def firstLast(webpage): f = open(webpage) lines = f.readlines() f.close() print firstNonBlank(lines), lines.reverse() print firstNonBlank(lines), def download(url='http://www',process=firstLast): try: retval = urlretrieve(url)[0] except IOError: retval = None if retval: process(retval) if __name__ == '__main__': download()
利用urllib模塊,來實現(xiàn)一個網(wǎng)頁中針對圖片的抓取功能:
import urllib.request import socket import re import sys import os targetDir = r"C:\Users\elqstux\Desktop\pic" def destFile(path): if not os.path.isdir(targetDir): os.mkdir(targetDir) pos = path.rindex('/') t = os.path.join(targetDir, path[pos+1:]) return t if __name__ == "__main__": hostname = "http://www.douban.com" req = urllib.request.Request(hostname) webpage = urllib.request.urlopen(req) contentBytes = webpage.read() for link, t in set(re.findall(r'(http:[^\s]*?(jpg|png|gif))', str(contentBytes))): print(link) urllib.request.urlretrieve(link, destFile(link))
import urllib.request import socket import re import sys import os targetDir = r"H:\pic" def destFile(path): if not os.path.isdir(targetDir): os.mkdir(targetDir) pos = path.rindex('/') t = os.path.join(targetDir, path[pos+1:]) #會以/作為分隔 return t if __name__ == "__main__": hostname = "http://www.douban.com/" req = urllib.request.Request(hostname) webpage = urllib.request.urlopen(req) contentBytes = webpage.read() match = re.findall(r'(http:[^\s]*?(jpg|png|gif))', str(contentBytes) )#r'(http:[^\s]*?(jpg|png|gif))'中包含兩層圓括號,故有兩個分組, #上面會返回列表,括號中匹配的內(nèi)容才會出現(xiàn)在列表中 for picname, picType in match: print(picname) print(picType) ''''' 輸出: http://img3.douban.com/pics/blank.gif gif http://img3.douban.com/icon/g111328-1.jpg jpg http://img3.douban.com/pics/blank.gif gif http://img3.douban.com/icon/g197523-19.jpg jpg http://img3.douban.com/pics/blank.gif gif ... '''
相關(guān)文章
Python讀取mat文件,并轉(zhuǎn)為csv文件的實例
今天小編就為大家分享一篇Python讀取mat文件,并轉(zhuǎn)為csv文件的實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-07-07python與js主要區(qū)別點(diǎn)總結(jié)
在本篇內(nèi)容里小編給大家整理了關(guān)于python與js主要區(qū)別點(diǎn)總結(jié)內(nèi)容,有興趣的朋友們可以學(xué)習(xí)下。2020-09-09python 對dataframe下面的值進(jìn)行大規(guī)模賦值方法
今天小編就為大家分享一篇python 對dataframe下面的值進(jìn)行大規(guī)模賦值方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-06-06詳解OpenCV自適應(yīng)直方圖均衡化的應(yīng)用
在本文中,將介紹如何應(yīng)用對比度受限的自適應(yīng)直方圖均衡化 ( Contrast Limited Adaptive Histogram Equalization, CLAHE ) 來均衡圖像,需要的可以參考一下2022-02-02