# xpath语法可参考http://www.w3school.com.cn/xpath/xpath_syntax.asp
# 本博客引用于https://zhuanlan.zhihu.com/something-python?topic=Python # coding:utf-8
import requests
from lxml import html
import os
import time def header(referer):
headers = {
'Host': 'i.meizitu.net',
'Pragma': 'no-cache',
'Accept-Encoding': 'gzip, deflate',
'Accept-Language': 'zh-CN,zh;q=0.8,en;q=0.6',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive',
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/537.36 (KHTML, like Gecko) '
'Chrome/59.0.3071.115 Safari/537.36',
'Accept': 'image/webp,image/apng,image/*,*/*;q=0.8',
'Referer': '{}'.format(referer),
}
return headers # 获取主页列表, 解析 html 的话最好使用html.fromstring(),它有xpath函数,可用于定位元素。
def getPage(pageNum):
baseUrl = 'http://www.mzitu.com/page/{}'.format(pageNum)
selector = html.fromstring(requests.get(baseUrl).content)
urls = []
for i in selector.xpath('//ul[@id="pins"]/li/a/@href'):
urls.append(i)
print(i)
return urls # 图片链接列表, 标题
# url是详情页链接
def getPiclink(url):
sel = html.fromstring(requests.get(url).content)
# 图片总数,xpath 表达式应该返回元素的话,总是返回一个数组,即使只有一个元素;其中@class表示属性class;last()函数表示最后一个a标签
total = sel.xpath('//div[@class="pagenavi"]/a[last()-1]/span/text()')[0]
# 标题
title = sel.xpath('//h2[@class="main-title"]/text()')[0]
# 文件夹格式
dirName = u"【{}P】{}".format(total, title)
# 新建文件夹
os.mkdir(dirName) n = 1
for i in range(int(total)):
# 每一页
try:
link = '{}/{}'.format(url, i+1)
s = html.fromstring(requests.get(link).content)
# 图片地址在src标签中
jpgLink = s.xpath('//div[@class="main-image"]/p/a/img/@src')[0]
# print(jpgLink)
# 文件写入的名称:当前路径/文件夹/文件名
filename = '%s/%s/%s.jpg' % (os.path.abspath('.'), dirName, n)
print(u'开始下载图片:%s 第%s张' % (dirName, n))
#"wb+" 以二进制写方式打开,可以读、写文件, 如果文件不存在,创建该文件
with open(filename, "wb+") as jpg:
jpg.write(requests.get(jpgLink, headers=header(jpgLink)).content)
n += 1
except:
pass #下面一行代码的作用:文件作为脚本直接执行才会被执行下面代码,而import到其他脚本中是不会被执行的,http://www.dengfeilong.com/post/60.html
if __name__ == '__main__':
pageNum = input(u'请输入页码:')
p = getPage(pageNum)
for e in p:
print(e)
getPiclink(e)
# lxml的报错
time.sleep(2) # 执行的时候用python3, 并且要安装pip install lxml requests
#虚拟环境中装python3
#sudo apt-get install python-pip
#sudo apt-get install python-virtualenv #安装本地虚拟环境管理工具
#mkdir ~/django # 创建目录
#cd ~/django virtualenv venv #在~/django目录下,创建一个venv的虚拟环境
#source venv/bin/activate #开启虚拟环境

  

用xpath来爬图的更多相关文章

  1. Python多线程爬图&Scrapy框架爬图

    一.背景 对于日常Python爬虫由于效率问题,本次测试使用多线程和Scrapy框架来实现抓取斗图啦表情.由于IO操作不使用CPU,对于IO密集(磁盘IO/网络IO/人机交互IO)型适合用多线程,对于 ...

  2. requests+xpath+map爬取百度贴吧

    # requests+xpath+map爬取百度贴吧 # 目标内容:跟帖用户名,跟帖内容,跟帖时间 # 分解: # requests获取网页 # xpath提取内容 # map实现多线程爬虫 impo ...

  3. python学习之BeautifulSoup模块爬图

    BeautifulSoup模块爬图学习HTML文本解析标签定位网上教程多是爬mzitu,此网站反爬限制多了.随意找了个网址,解析速度有些慢.脚本流程:首页获取总页数-->拼接每页URL--> ...

  4. 【个人】爬虫实践,利用xpath方式爬取数据之爬取虾米音乐排行榜

    实验网站:虾米音乐排行榜 网站地址:http://www.xiami.com/chart  难度系数:★☆☆☆☆ 依赖库:request.lxml的etree (安装lxml:pip install ...

  5. 爬虫(Xpath)——爬tieba.baidu.com

    工具:python3 核心知识点: 1)lxml包不能用pip下载,因为里面有其他语言编写的文件 2)urlopen返回的请求是html文件,要使用 content = etree.HTML(html ...

  6. 一起学爬虫——使用xpath库爬取猫眼电影国内票房榜

    之前分享了一篇使用requests库爬取豆瓣电影250的文章,今天继续分享使用xpath爬取猫眼电影热播口碑榜 XPATH语法 XPATH(XML Path Language)是一门用于从XML文件中 ...

  7. Java - XPath解析爬取内容

    code { margin: 0; padding: 0; white-space: pre; border: none; background: transparent; } pre { backg ...

  8. Scrapy中用xpath/css爬取豆瓣电影Top250:解决403HTTP status code is not handled or not allowed

    好吧,我又开始折腾豆瓣电影top250了,只是想试试各种方法,看看哪一种的方法效率是最好的,一直进行到这一步才知道 scrapy的强大,尤其是和selector结合之后,速度飞起.... 下面我就采用 ...

  9. Python 2.7_利用xpath语法爬取豆瓣图书top250信息_20170129

    大年初二,忙完家里一些事,顺带有人交流爬取豆瓣图书top250 1.构造urls列表 urls=['https://book.douban.com/top250?start={}'.format(st ...

随机推荐

  1. [Unity Shader笔记]渲染路径--Forward渲染路径

    [Unity Shader笔记]渲染路径--Forward渲染路径 (2014-04-22 20:08:25) 转载▼ 标签: shader unity renderingpath forward 游 ...

  2. 学习h5(开始)

    webstorm 下载地址:http://www.sdifenzhou.com/6176.html webstorm注册码: 43B4A73YYJ-eyJsaWNlbnNlSWQiOiI0M0I0QT ...

  3. zookeeper和duboo 没用

    什么是dubbo Dubbo是阿里巴巴SOA服务化治理方案的核心框架,是一个分布式服务框架,致力于提供高性能和透明化的RPC远程服务调用方案,以及SOA服务治理方案. 测试和生产公用一套zookeep ...

  4. poi导出excle测试类

    package poiexcel; import java.util.ArrayList; import java.util.List; public class Test { public stat ...

  5. LoadRunner11学习记录六 -- 服务器分析

    LoadRunner运行时,怎么利用服务器的一些参数进行分析: 1.内存分析方法 内存分析方法主要是用于判断系统有无遇到内存瓶颈,是否需要通过增加内存等手段提高系统性能表现.主要计数器包括Memory ...

  6. XSS的原理分析与解剖:第三章(技巧篇)【转】

    0×01 前言: 关于前两节url: 第一章:http://www.freebuf.com/articles/web/40520.html 第二章:http://www.freebuf.com/art ...

  7. j中的substr(start,length)和substring(start,stop)

    j中的substr(start,length)和substring(start,end) substring 1 substring 方法用于提取字符串中介于两个指定下标之间的字符(包头不包尾) 2 ...

  8. Unable to locate JAR/zip in file system as specified by the driver definition: ojdbc14.jar

    eclipse的配置错误,把当前包删除,重新导入一个包.然后设置与需要的数据库对应,就可以了

  9. 如何Android中加入扫描名片功能

    要想实现android手机通过扫描名片,得到名片信息,可以使用脉可寻提供的第三方SDK,即Maketion ScanCard SDK,脉可寻云名片识别服务.他们的官方网站为http://www.mak ...

  10. How to count the number of threads in a process on Linux

    If you want to see the number of threads per process in Linux environments, there are several ways t ...