最最最最簡單的python爬蟲操作

最近初學了python,就嘗試了一下非常簡單的爬蟲(爬取網頁的圖片存到本機上)。適合開始學習python的小白。

環境:python3.0。

上代碼:

import re
import urllib.request

def get_content(url):
# 定義一個抓取的函數
     html =urllib.request.urlopen(url)
     content =html.read().decode('utf-8')
     html.close()
     return content

def get_images(info):
# 定義一個保存圖片到本地的函數
     src =r'<img class="BDE_Image" src="(.+?\.jpg)"'
     comp =re.compile(src)
     get_codes =re.findall(comp,info)
     i = 1
     for get_code in get_codes:
          urllib.request.urlretrieve(get_code,r'D:\pythonPicture\%s.jpg'%i)#地址爲絕對路徑
          i =i + 1
info =get_content('http://tieba.baidu.com/p/5914519867') # 爬取圖片的網頁鏈接
get_images(info)
print("完成") #完成

 

運行如下:

 

這樣在pythonPicture文件夾中就爬取了百度貼吧的圖片了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章