利用Python网络爬虫抓取豆瓣首页图片代码分享
2017-07-24 20:25
856 查看
# 爬取豆瓣上的图片 import urllib.request import ssl import re #定义一个能够从html文件里面利用正则表达式抓取出图片地址的函数 def getImgLinks(html): imgRe = re.compile(r'<img.*?(http[\w/:\.-]+?\.jpg).*?') imgLinks = imgRe.findall(html) print(list(imgLinks)) return imgLinks #打开具体的网址,并抓取其html页面 context = ssl._create_unverified_context() weburl = "https://www.douban.com/"#要爬取图片所在的网址 # weburl = "https://www.sina.com.cn/" webheader = { 'Accept': 'text/html, application/xhtml+xml, */*', 'Accept-Language': 'zh-CN', 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko', 'DNT': '1', 'Connection': 'Keep-Alive', } req = urllib.request.Request(url=weburl,headers=webheader)#构造请求报头 webPage = urllib.request.urlopen(req,context=context) data = webPage.read().decode('utf-8') print("抓取网页成功") #主函数,依次捕获图片 imgLinks = getImgLinks(data) print(len(imgLinks)) count = 0 localStorePath = "D:/Python学习" for imgLink in imgLinks: count += 1 print('现在开始抓取第{}个图片,其地址是{}'.format(count,imgLink)) try: #以数字序号命名图片的两种方式 # urllib.request.urlretrieve(imgLink, localStorePath + '/%s.jpg'%count) # urllib.request.urlretrieve(imgLink, localStorePath + '/{}.jpg'.format(count)) #以图片本身的名字命名 print(re.findall(r'([\w-]+)\.jpg',imgLink)[0]) urllib.request.urlretrieve(imgLink, localStorePath + '/{}.jpg'.format(re.findall(r'([\w-]+)\.jpg',imgLink)[0]))#以地址为文件名保存 except: print('抓取第{}个时出现问题'.format(count)) continue 这是我自己写的代码,有两个方面供大家和大家分享,一是抓取html页面的时候规避ssl证书错误,二是保存图片时命名的方式。
相关文章推荐
- 【初学Python】利用python抓取bing首页图片
- Python -- 网络编程 -- 抓取网页图片 -- 豆瓣妹子
- [Python]网络爬虫(二):利用urllib2通过指定的URL抓取网页内容
- python3抓取异步百度瀑布流动态图片(二)get、json下载代码讲解
- python爬虫入门教程之点点美女图片爬虫代码分享
- [Python]网络爬虫(二):利用urllib2通过指定的URL抓取网页内容
- 零基础写python爬虫之抓取糗事百科代码分享
- Python实现简单网页图片抓取完整代码实例
- [Python]网络爬虫(二):利用urllib2通过指定的URL抓取网页内容
- 利用python抓取网页图片
- Python网络爬虫小试刀——抓取ZOL桌面壁纸图片2
- 利用python抓取豆瓣top500的电影
- [Python爬虫] 之二十六:Selenium +phantomjs 利用 pyquery抓取智能电视网站图片信息
- 零基础写python爬虫之抓取百度贴吧代码分享
- Python抓取图片小代码
- python抓取豆瓣妹子图片并上传到七牛
- 利用Python抓取图片
- python获取豆瓣电影简介代码分享