本博文学自卧槽哥:采用Python2.7版本
http://cuiqingcai.com/3179.html
关于转码问题的解决原链接
下面说方法:
import sys
reload(sys)
sys.setdefaultencoding(‘utf-8’)
path = str(title).strip().decode(‘utf-8’)
os.makedirs(os.path.join(“D:\mzitu”, path))
oschdir(“D:\mzitu\” + path)
附上代码:
# -*- coding:utf-8 -*-
import requests ##导入requests
from bs4 import BeautifulSoup ##导入bs4中的BeautifulSoup
import os
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
headers = {'User-Agent':"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/22.0.1207.1 Safari/537.1"}##浏览器请求头(大部分网站没有这个请求头会报错、请务必加上哦)
all_url = 'http://www.mzitu.com/all' ##开始的URL地址
start_html = requests.get(all_url, headers=headers) ##使用requests中的get方法来获取all_url(就是:http://www.mzitu.com/all这个地址)的内容 headers为上面设置的请求头、请务必参考requests官方文档解释
#print(start_html.text) ##打印出start_html (请注意,concent是二进制的数据,一般用于下载图片、视频、音频、等多媒体内容是才使用concent, 对于打印网页内容请使用text)
#text 尤为重要,谨记
Soup = BeautifulSoup(start_html.text, 'lxml')
##li_list = Soup.find_all('li')
##
##for li in li_list:
## print(li)
all_a = Soup.find('div', class_='all').find_all('a')
for a in all_a:
## print(a)
#创建文件夹
title = a.get_text()
path = str(title).strip().decode('utf-8')
os.makedirs(os.path.join("D:/mzitu", path))
os.chdir('D:/mzitu//'+title)
href = a['href']
#print title, href
html = requests.get(href, headers = headers)
html_Soup = BeautifulSoup(html.text, 'lxml')
max_span = html_Soup.find_all('span')[10].get_text()
for page in range(1, int(max_span)+1):
page_url = href + '/' + str(page)
#print(page_url)
img_html = requests.get(page_url, headers = headers)
img_Soup = BeautifulSoup(img_html.text, 'lxml')
img_url = img_Soup.find('div', class_='main-image').find('img')['src']
#print(img_url)
name = img_url[-9:-4]
img = requests.get(img_url, headers = headers)
f = open(name+'.jpg', 'ab')
f.write(img.content)
f.close()