使用Python3編寫抓取網頁和只抓網頁圖片的指令碼

來源:互聯網
上載者:User
最基本的抓取網頁內容的代碼實現:

#!/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模組,來實現一個網頁中針對圖片的抓取功能:

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))'中包含兩層圓括弧,故有兩個分組,                              #上面會返回列表,括弧中匹配的內容才會出現在列表中   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 ... ''' 
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.