原文:http://wuchong.me/blog/2014/01/27/python-spider-gif/
原博主是用的python3.5 我是python2.7 稍作修改其中的代码。有几处还是要特别注意的
代码如下
# coding=utf-8
import sys
import urllib
import bs4
import os
import requests
reload(sys)
sys.setdefaultencoding('utf-8')
page_sum = 1 # 设置下载页数
path = os.getcwd()
path = os.path.join(path, u'暴走GIF')
if not os.path.exists(path):
os.mkdir(path)
url = "http://baozoumanhua.com/gif/year/page/" # url地址
headers = { # 伪装浏览器
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko)'
' Chrome/32.0.1700.76 Safari/537.36'
}
for count in range(page_sum):
url += str(count + 1)
req = requests.get(url=url, headers=headers)
content = req.content
# content = urllib.urlopen(url).read()
soup = bs4.BeautifulSoup(content, "html.parser")
img_content = soup.findAll('img', attrs={'style': 'width:460px'})
url_list = [img['src'] for img in img_content] # 列表推导 url
title_list = [img['alt'] for img in img_content] # 图片名称
for i in range(url_list.__len__()):
imgurl = url_list[i]
filename = path + os.sep + title_list[i] + ".gif"
filename_new = filename.replace('?', "").replace('..', "").replace('><', "")
print(filename1 + '\n' + imgurl) # 打印下载信息
urllib.urlretrieve(imgurl, filename_new) #下载图片
思路
1:使用requests 模块下载网页内容
2:使用bs4模块解析网页
3:使用findall 找到满足条件的内容
网页源码如下:
<img alt="他的足球梦" data-original-image-url="http://wanzao2.b0.upaiyun.com/system/pictures/23281453/original/1431244036_250x172.gif" src="http://ww3.sinaimg.cn/large/005XNr41jw1erz7ddwj55g306y04s7gu.gif" style="width:460px" data-bd-imgshare-binded="1">
4:找到alt:标题 和src:资源
5:使用urllib.urlretrieve 方法下载。
遇到的问题
1:
soup = bs4.BeautifulSoup(content, "html.parser") #必须加上"html.parser" 参数
*不然会报以下错误:
'''
UserWarning: No parser was explicitly specified, so I'm using the best available HTML parser for this system ("html.parser"). This usually isn't a problem, but if you run this code on another system, or in a different virtual environment, it may use a different parser and behave differently.
To get rid of this warning, change this:
BeautifulSoup([your markup])
to this:
BeautifulSoup([your markup], "html.parser")
markup_type=markup_type))*
'''
因为这个问题google了好久。
2:下载gif的时候,必须把gif 中的 带的一些特殊字符 替换掉
filename.replace('?', "").replace('..', "").replace('><', "")
就这些了。首次学习requests模块和bs4,这个是最简单的方法了,当然,如果你正则比较好,可以使用urllib urllib2 模块爬取,其实代码还可以修改下。暂时懒得弄了。