国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

使用Python3編寫抓取網(wǎng)頁和只抓網(wǎng)頁圖片的腳本

2019-11-25 17:05:09
字體:
供稿:網(wǎng)友

最基本的抓取網(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 ... ''' 

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 平远县| 军事| 顺昌县| 拉孜县| 沽源县| 进贤县| 临洮县| 龙胜| 托克逊县| 武威市| 琼中| 淮阳县| 黄石市| 肇东市| 客服| 潼南县| 新邵县| 连城县| 精河县| 驻马店市| 远安县| 都江堰市| 石嘴山市| 柳江县| 石屏县| 山西省| 阜城县| 兴隆县| 盐山县| 察雅县| 外汇| 宾川县| 平塘县| 呈贡县| 宝鸡市| 曲沃县| 依兰县| 湖南省| 石楼县| 庆城县| 德保县|