日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

用Python 爬虫爬取贴吧图片

發布時間:2024/1/18 python 41 豆豆
生活随笔 收集整理的這篇文章主要介紹了 用Python 爬虫爬取贴吧图片 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

之前一直在看機器學習,遇到了一些需要爬取數據的內容,于是稍微看了看Python爬蟲,在此適當做一個記錄。我也沒有深入研究爬蟲,大部分均是參考了網上的資源。

先推薦兩個Python爬蟲的教程,網址分別是http://cuiqingcai.com/1052.html 和 http://ddswhu.com/2015/03/25/python-downloadhelper-premium/ ,我就是看這兩個當做基本的入門。

有興趣才有動力,既然學了爬蟲,那就先爬取美女照片吧。當然,這里先并不是爬取好友的照片了,比如QQ空間、人人之類的,因為這些還涉及模擬登錄之類的操作。為了方便,還是爬取貼吧里的圖片。主要是參考了Github上這個項目:https://github.com/Yixiaohan/show-me-the-code (Python 練習冊,每天一個小項目),感覺還是很不錯的。

先來看上面那個項目里的第13題,要求是爬取這個網址中的圖片:http://tieba.baidu.com/p/2166231880,參考了網友renzongxian 的代碼(使用版本為Python 3.4),如下:

# 爬取貼吧圖片,網址:http://tieba.baidu.com/p/2166231880import urllib.request import re import osdef fetch_pictures(url):html_content = urllib.request.urlopen(url).read()r = re.compile('<img pic_type="0" class="BDE_Image" src="(.*?)"')picture_url_list = r.findall(html_content.decode('utf-8'))os.mkdir('pictures')os.chdir(os.path.join(os.getcwd(), 'pictures'))for i in range(len(picture_url_list)):picture_name = str(i) + '.jpg'try:urllib.request.urlretrieve(picture_url_list[i], picture_name)print("Success to download " + picture_url_list[i])except:print("Fail to download " + picture_url_list[i])if __name__ == '__main__':fetch_pictures("http://tieba.baidu.com/p/2166231880")

運行之后,會生成一個名為pictures的文件夾,自動下載圖片并存放進去(圖片就不截圖了)。

為了測試該程序,我看了另一個Python爬蟲的代碼,準備把網址替換一下,即爬取這個網址中的圖片:http://tieba.baidu.com/p/2460150866 ,只需要將上述代碼稍作修改(把網址換一下,文件夾改一下)即可,如下

# 爬取貼吧圖片,網址:http://tieba.baidu.com/p/2460150866import urllib.request import re import osdef fetch_pictures(url):html_content = urllib.request.urlopen(url).read()r = re.compile('<img pic_type="0" class="BDE_Image" src="(.*?)"')picture_url_list = r.findall(html_content.decode('utf-8'))os.mkdir('photos')os.chdir(os.path.join(os.getcwd(), 'photos'))for i in range(len(picture_url_list)):picture_name = str(i) + '.jpg'try:urllib.request.urlretrieve(picture_url_list[i], picture_name)print("Success to download " + picture_url_list[i])except:print("Fail to download " + picture_url_list[i])if __name__ == '__main__':fetch_pictures("http://tieba.baidu.com/p/2460150866")

爬取的圖片會存放在photos文件夾中,截圖如下:

好的,那下面就來爬取一組明星的圖片吧,比如劉詩詩,網址如下:http://tieba.baidu.com/p/2854146750 ,如果仍然直接把代碼中的網址和文件夾名改一下,會發現并沒有下載成功。所以,編程還是得老老實實看代碼啊,光想著直接換個網址實在太偷懶(當然,想法可以有,這樣才可以寫出更智能、更進步的程序嘛)。

代碼在抓取網頁之后,利用正則表達式找到了圖片的網址(URL),即關鍵在代碼的這一行

r = re.compile('<img pic_type="0" class="BDE_Image" src="(.*?)"')

上面那兩個例子之所以會成功,是因為網頁源代碼中(可以用谷歌瀏覽器查看)圖片的網址確實是這個形式的,所以匹配到了。而劉詩詩照片的網址呢,查看一下,是這樣的:

也就是里面img標簽里的代碼形式是不一樣的,不是

<img pic_type="0" class="BDE_Image" src="(.*?)"

而是

<img class="BDE_Image" src="(.*?)" pic_ext="jpeg" pic_type="0"

所以要把正則表達式的內容修改一下,整體代碼如下:

# 爬取貼吧劉詩詩的圖片,網址:http://tieba.baidu.com/p/2854146750import urllib.request import re import osdef fetch_pictures(url):html_content = urllib.request.urlopen(url).read()r = re.compile('<img class="BDE_Image" src="(.*?)" pic_ext="jpeg" pic_type="0"')picture_url_list = r.findall(html_content.decode('utf-8'))os.mkdir('liushishi')os.chdir(os.path.join(os.getcwd(), 'liushishi'))for i in range(len(picture_url_list)):picture_name = str(i) + '.jpg'try:urllib.request.urlretrieve(picture_url_list[i], picture_name)print("Success to download " + picture_url_list[i])except:print("Fail to download " + picture_url_list[i])if __name__ == '__main__':fetch_pictures("http://tieba.baidu.com/p/2854146750")

運行后,爬取成功,截圖如下:

嗯,這種用代碼自動下載的感覺就是爽!(哈哈,逃)

所以下載圖片的關鍵在于正則表達式的匹配。下面再舉兩個例子。

先來一個簡單的。網址是:http://tieba.baidu.com/p/3884688092 ,代碼如下:

# 爬取貼吧圖片,網址:http://tieba.baidu.com/p/3884688092import urllib.request import re import osdef fetch_pictures(url):html_content = urllib.request.urlopen(url).read()r = re.compile('<img class="BDE_Image" pic_type="\d" width="\d\d\d" height="\d\d\d" src="(.*?)"')picture_url_list = r.findall(html_content.decode('utf-8'))os.mkdir('test')os.chdir(os.path.join(os.getcwd(), 'test'))for i in range(len(picture_url_list)):picture_name = str(i) + '.jpg'try:urllib.request.urlretrieve(picture_url_list[i], picture_name)print("Success to download " + picture_url_list[i])except:print("Fail to download " + picture_url_list[i])if __name__ == '__main__':fetch_pictures("http://tieba.baidu.com/p/3884688092")

關鍵仍在于正則表達式那一行:

r = re.compile('<img class="BDE_Image" pic_type="\d" width="\d\d\d" height="\d\d\d" src="(.*?)"')

不過我寫的匹配比較拙劣,也就爬取了前4張圖片而已,有待完善。

再來一個自己喜歡的。之前看到了一個人手繪龍珠的圖片,就想爬取下來,網址在:http://tieba.baidu.com/p/3720487356 ,代碼如下:

# 爬取貼吧龍珠圖片,網址:http://tieba.baidu.com/p/3720487356import urllib.request import re import osdef fetch_pictures(url):html_content = urllib.request.urlopen(url).read()r = re.compile('<img class="BDE_Image" pic_type="0" width="\d\d\d" height="\d\d\d" src="(.*?)"')picture_url_list = r.findall(html_content.decode('utf-8'))os.mkdir('longzhu')os.chdir(os.path.join(os.getcwd(), 'longzhu'))for i in range(len(picture_url_list)):picture_name = str(i) + '.jpg'try:urllib.request.urlretrieve(picture_url_list[i], picture_name)print("Success to download " + picture_url_list[i])except:print("Fail to download " + picture_url_list[i])if __name__ == '__main__':fetch_pictures("http://tieba.baidu.com/p/3720487356")

效果也不是很好,只是爬取了首頁的5張圖而已:

以上代碼均是用Python 3.4寫的。不過,用Python 2爬蟲也很方便,于是也參考了網上Python 2爬蟲的代碼。

先看一個網上的示例(不好意思,又是爬取美女圖片,網上爬美女程序太多),是用Python 2.7寫的:

#!/bin/env python # -*- coding: utf-8 -*- # 爬取網上圖片,網址:http://jandan.net/ooxx#導入模塊 import urllib2 import re import os import glob#設定抓取頁數 page_amount = 2#抓取首頁的html代碼 def get_page(url):req = urllib2.Request(url)req.add_header('User-Agent','Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.111 Safari/537.36') #缺省部分填上瀏覽器字符串response = urllib2.urlopen(req)html = response.read().decode('utf-8')return html#抓取圖片 def read_image(url):req = urllib2.Request(url)req.add_header('User-Agent','Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.111 Safari/537.36') #缺省部分填上瀏覽器字符串response = urllib2.urlopen(url)html = response.read()return html#得到當前的最新頁面數,從這個頁面開始倒著爬,因為用了這個腳本以后以前的圖可能已經看過了 def get_current_page_number(html):match = re.search(r'<span class="current-comment-page">\[(.*)\]</span>',html)return match.group(1)#得到圖片列表 def get_picturs_url_list(url):html = get_page(url)l = re.findall(r'<p><img src="http://.*.sinaimg.cn/mw600/.*jpg" /></p>',html)result = []for string in l:src = re.search(r'"(.*)"',string)result.append(str(src.group(1))) #解決Unicode編碼開頭問題,有空好好補下編碼和字符規范return result#下載圖片并存儲到本地文件夾 def image_save(url,number):number = str(number)print '正在抓取第',number,'張'filename = number + '.jpg'with open(filename,'wb') as fp:img = read_image(url)fp.write(img)#準備存放圖片的文件夾,并進入到指定路徑 def floder_prepare(floder):a = glob.glob('*')if floder not in a:os.mkdir(floder)os.chdir(floder)#主函數 def main():html = get_page('http://jandan.net/ooxx')number = int(get_current_page_number(html))l = []amount = 0for n in range(0,page_amount):url = 'http://jandan.net/ooxx/page-' + str(number-n) + '#comments'l += get_picturs_url_list(url) floder_prepare('picture')for url in l:amount += 1image_save(url,amount)if __name__ == '__main__':main()print '全部抓完啦'

上面的程序也是自動下載圖片,并自動建立了一個pciture文件夾存放(圖片就不截圖了)。于是我就把它適當修改用來重新爬取上面的龍珠圖片,代碼如下:

#!/bin/env python # -*- coding: utf-8 -*- # 爬取網上圖片,網址:http://tieba.baidu.com/p/3720487356#導入模塊 import urllib2 import re import os import glob#設定抓取頁數 page_amount = 5#抓取首頁的html代碼 def get_page(url):req = urllib2.Request(url)req.add_header('User-Agent','Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.111 Safari/537.36') #缺省部分填上瀏覽器字符串response = urllib2.urlopen(req)html = response.read().decode('utf-8')return html#抓取圖片 def read_image(url):req = urllib2.Request(url)req.add_header('User-Agent','Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.111 Safari/537.36') #缺省部分填上瀏覽器字符串response = urllib2.urlopen(url)html = response.read()return html#得到圖片列表 def get_picturs_url_list(url):html = get_page(url)l = re.findall(r'<img class="BDE_Image" pic_type="0" width="\d\d\d" height="\d\d\d" src="(.*?)"',html)return l#下載圖片并存儲到本地文件夾 def image_save(url,number):number = str(number)print '正在抓取第',number,'張'filename = number + '.jpg'with open(filename,'wb') as fp:img = read_image(url)fp.write(img)#準備存放圖片的文件夾,并進入到指定路徑 def floder_prepare(floder):a = glob.glob('*')if floder not in a:os.mkdir(floder)os.chdir(floder)#主函數 def main():number = 5l = []amount = 0for n in range(0,page_amount):url = 'http://tieba.baidu.com/p/3720487356?pn=' + str(number-n)l += get_picturs_url_list(url) floder_prepare('pics_longzhu')for url in l:amount += 1image_save(url,amount)if __name__ == '__main__':main()print '全部抓完啦'

由于這個帖子目前總共有5頁,所以就設定了爬取頁數,然后從最后一頁倒著逐頁全部爬取下來了,截圖如下:

嗯,果然效果好了不少。當然,用Python 2爬取圖片的代碼還有很多,以Github上那個項目里的13題為例,最后再貼兩個代碼以供交流學習。

代碼(1)

# -*- coding: utf-8 -*- # 爬取貼吧圖片,網址:http://tieba.baidu.com/p/2166231880import urllib2 from HTMLParser import HTMLParser from traceback import print_exc from sys import stderrclass _DeHTMLParser(HTMLParser):'''利用HTMLParse來解析網頁元素'''def __init__(self):HTMLParser.__init__(self)self.img_links = []def handle_starttag(self, tag, attrs):if tag == 'img':# print(attrs)try:if ('pic_type','0') in attrs:for name, value in attrs:if name == 'src':self.img_links.append(value)except Exception as e:print(e)return self.img_linksdef dehtml(text):try:parser = _DeHTMLParser()parser.feed(text)parser.close()return parser.img_linksexcept:print_exc(file=stderr)return textdef main():html = urllib2.urlopen('http://tieba.baidu.com/p/2166231880')content = html.read()print(dehtml(content))i = 0for img_list in dehtml(content):img_content = urllib2.urlopen(img_list).read()path_name = str(i)+'.jpg'with open(path_name,'wb') as f:f.write(img_content)i+=1if __name__ == '__main__':main()

代碼(2)

# coding:utf-8 # 爬取貼吧圖片,網址:http://tieba.baidu.com/p/2166231880import requests, re, osurl = 'http://tieba.baidu.com/p/2166231880'header = {'Accept': '*/*','Accept-Encoding':'gzip,deflate,sdch','Accept-Language':'zh-CN,zh;q=0.8','Connection':'keep-alive'} html = requests.get(url,headers = header)data = html.content.decode('utf-8') find = re.compile(r'<img pic_type="0" class="BDE_Image" src="(.*?).jpg" bdwater') result = find.findall(data)for img_url in result:name = img_url.split('/')[-1]img_url = img_url+'.jpg'html = requests.get(img_url,headers = header)im = html.contentwith open(name+'.jpg','wb')as f:f.write(im)

總結

以上是生活随笔為你收集整理的用Python 爬虫爬取贴吧图片的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。