0
点赞
收藏
分享

微信扫一扫

34 爬虫 - XPath实例测试

古月无语 2022-03-23 阅读 52


1. 获取所有的​​<li>​​ 标签

# xpath_li.py

from lxml import etree

html = etree.parse('hello.html')
print type(html) # 显示etree.parse() 返回类型

result = html.xpath('//li')

print result # 打印<li>标签的元素集合
print len(result)
print type(result)
print type(result[0])

输出结果:

<type 'lxml.etree._ElementTree'>
[<Element li at 0x1014e0e18>, <Element li at 0x1014e0ef0>, <Element li at 0x1014e0f38>, <Element li at 0x1014e0f80>, <Element li at 0x1014e0fc8>]
5
<type 'list'>
<type 'lxml.etree._Element'>

2. 继续获取​​<li>​​​ 标签的所有 ​​class​​属性

# xpath_li.py

from lxml import etree

html = etree.parse('hello.html')
result = html.xpath('//li/@class')

print result

运行结果:

['item-0', 'item-1', 'item-inactive', 'item-1', 'item-0']

3. 继续获取​​<li>​​​标签下​​hre​​​ 为 ​​link1.html​​​的​​<a>​​标签

# xpath_li.py

from lxml import etree

html = etree.parse('hello.html')
result = html.xpath('//li/a[@href="link1.html"]')

print result

运行结果

[<Element a at 0x10ffaae18>]

4. 获取​​<li>​​​ 标签下的所有 ​​<span>​​ 标签

# xpath_li.py

from lxml import etree

html = etree.parse('hello.html')

#result = html.xpath('//li/span')
#注意这么写是不对的:
#因为 / 是用来获取子元素的,而 <span> 并不是 <li> 的子元素,所以,要用双斜杠

result = html.xpath('//li//span')

print result

运行结果

[<Element span at 0x10d698e18>]

5. 获取 ​​<li>​​​ 标签下的​​<a>​​标签里的所有 class

# xpath_li.py

from lxml import etree

html = etree.parse('hello.html')
result = html.xpath('//li/a//@class')

print result

运行结果

['blod']

6. 获取最后一个 ​​<li>​​​ 的 ​​<a>​​ 的 href

# xpath_li.py

from lxml import etree

html = etree.parse('hello.html')

result = html.xpath('//li[last()]/a/@href')
# 谓语 [last()] 可以找到最后一个元素

print result

运行结果

['link5.html']

7. 获取倒数第二个元素的内容

# xpath_li.py

from lxml import etree

html = etree.parse('hello.html')
result = html.xpath('//li[last()-1]/a')

# text 方法可以获取元素内容
print result[0].text

运行结果

fourth item

8. 获取 class 值为 bold 的标签名

# xpath_li.py

from lxml import etree

html = etree.parse('hello.html')

result = html.xpath('//*[@class="bold"]')

# tag方法可以获取标签名
print result[0].tag

运行结果

span



举报

相关推荐

0 条评论