# 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. Ubuntu设置屏幕分辨率

    Ubuntu设置屏幕分辨率 原创 2016年10月14日 13:01:24 14900 在虚拟机装好Ubuntu,进入系统分辨率是800*600,打开显示界面设置下分辨率,设置完怎么也选不上应用,于是 ...

  2. Fix: The account is not authorized to log in from this station

    If you have more the one computers running Windows, then its possible to connect them using HomeGrou ...

  3. Openssl gendsa命令

    一.简介 gendsa命令能够根据DSA密钥参数生成DSA密钥 二.语法 openssl gendsa [-out filename] [-passout out] [-rand file(s)] [ ...

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

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

  5. leetcode - 3、Longest Substring Without Repeating Characters

    题目链接:https://leetcode.com/problems/longest-substring-without-repeating-characters/description/ 题目要求: ...

  6. 详解Python垃圾回收机制

    http://www.qytang.com/cn/list/28/417.htmhttp://www.qytang.com/cn/list/28/416.htmhttp://ww 引用计数 Pytho ...

  7. [Training Video - 4] [Groovy] Initializing log inside class with constructor

    TestService s = new TestService(log,context,testRunner) s.xyz() class TestService{ def log def conte ...

  8. 【转】C++中#if #ifdef 的作用

    一般情况下,源程序中所有的行都参加编译.但是有时希望对其中一部分内容只在满足一定条件才进行编译,也就是对一部分内容指定编译的条件,这就是“条件 编译”.有时,希望当满足某条件时对一组语句进行编译,而当 ...

  9. 从零开始学习前端JAVASCRIPT — 9、JavaScript基础RegExp(正则表达式)

    1:正则的概念 正则表达式(regular expression)是一个描述字符规则的对象.可以用来检查一个字符串是否含有某个子字符串,将匹配的子字符串做替换或者从某个字符串中取出符合某个条件的子串等 ...

  10. mdb

    计划开发高性能KV数据库, 学习MongoDB leveldb innodb, 练手贴+日记贴: http://bbs.chinaunix.net/thread-4244870-1-1.html 超高 ...