本文章属于爬虫入门到精通系统教程第六讲
在爬虫入门到精通第五讲中,我们了解了如何用正则表达式去抓取我们想要的内容.这一章我们来学习如何更加简单的来获取我们想要的内容.
XPath即为XML路径语言(XML Path Language),它是一种用来确定XML文档中某部分位置的语言。 XPath基于XML的树状结构,提供在数据结构树中找寻节点的能力。起初XPath的提出的初衷是将其作为一个通用的、介于XPointer与XSL间的语法模型。但是XPath很快的被开发者采用来当作小型查询语言。
要使用xpath我们需要下载lxml,在爬虫入门到精通-环境的搭建(http://mp.weixin.qq.com/s?__biz=MzU2OTAxNTcwMw==&mid=100000022&idx=1&sn=a7091cd4b98790b6a4ed017921e757fb&chksm=7c846dee4bf3e4f83758b7c9a9bd75822b006770b71c7c29722f2c28840edfbc705951960d7f#rd)这一章也说明怎么装,如果还没有安装的话,那就去下载安装吧
直接看代码实战吧。
from lxml import etree
# 定义一个函数,给他一个html,返回xml结构
def getxpath(html):
return etree.HTML(html)
# 下面是我们实战的第一个html
sample1 = """
<html>
<head> <title>My page</title></head>
<body>
<h2>Welcome to my <a href="#" src="x">page</a></h2>
<p>This is the first paragraph.</p>
<!-- this is the end -->
</body>
</html>"""
# 获取xml结构
s1 = getxpath(sample1)
# 获取标题(两种方法都可以)#有同学在评论区指出我这边相对路径和绝对路径有问题,我搜索了下#发现定义如下图
s1.xpath('//title/text()')
s1.xpath('/html/head/title/text()')
相对路径与绝对路径
sample2 = """
<html>
<body>
<ul>
<li>Quote 1</li>
<li>Quote 2 with <a href="...">link</a></li>
<li>Quote 3 with <a href="...">another link</a></li>
<li><h2>Quote 4 title</h2> ...</li>
</ul>
</body>
</html>
"""
s2 = getxpath(sample2)
sample3 = """
<html>
<body>
<ul>
<li id="begin"><a href="https://scrapy.org">Scrapy</a>begin</li>
<li><a href="https://scrapinghub.com">Scrapinghub</a></li>
<li><a href="https://blog.scrapinghub.com">Scrapinghub Blog</a></li>
<li id="end"><a href="http://quotes.toscrape.com">Quotes To Scrape</a>end</li>
<li data-xxxx="end" abc="abc"><a href="http://quotes.toscrape.com">Quotes To Scrape</a>end</li>
</ul>
</body></html>"""
s3 = getxpath(sample3)
sample4 = u"""
<html>
<head>
<title>My page</title>
</head>
<body>
<h2>Welcome to my <a href="#" src="x">page</a></h2>
<p>This is the first paragraph.</p>
<p class="test">编程语言
<a href="#">python</a>
<img src="#" alt="test"/>javascript
<a href="#"><strong>C#</strong>JAVA</a>
</p>
<p class="content-a">a</p>
<p class="content-b">b</p>
<p class="content-c">c</p>
<p class="content-d">d</p>
<p class="econtent-e">e</p>
<p class="heh">f</p>
<!-- this is the end -->
</body>
</html>"""
s4 = etree.HTML(sample4)
看完本篇文章后,你应该要