获取所有li标签:
from lxml import etree
html = etree.parse('hello.html')
print type(html) # 显示etree.parse() 返回类型
result = html.xpath('//li')
print(result) # 打印<li>标签的元素集合
获取所有li元素下的所有class属性的值:
from lxml import etree
html = etree.parse('hello.html')
result = html.xpath('//li/@class')
print(result)
获取li标签下href为www.baidu.com的a标签:
from lxml import etree
html = etree.parse('hello.html')
result = html.xpath('//li/a[@href="www.baidu.com"]')
print(result)
获取li标签下所有span标签:
from lxml import etree
html = etree.parse('hello.html')
#result = html.xpath('//li/span')
#注意这么写是不对的:
#因为 / 是用来获取子元素的,而 <span> 并不是 <li> 的子元素,所以,要用双斜杠
result = html.xpath('//li//span')
print(result)
获取li标签下的a标签里的所有class:
from lxml import etree
html = etree.parse('hello.html')
result = html.xpath('//li/a//@class')
print(result)
获取最后一个li的a的href属性对应的值:
from lxml import etree
html = etree.parse('hello.html')
result = html.xpath('//li[last()]/a/@href')
# 谓语 [last()] 可以找到最后一个元素
print(result)
获取倒数第二个li元素的内容:
from lxml import etree
html = etree.parse('hello.html')
result = html.xpath('//li[last()-1]/a')
text 方法可以获取元素内容
print(result[0].text)
获取倒数第二个li元素的内容的第二种方式:
from lxml import etree
html = etree.parse('hello.html')
result = html.xpath('//li[last()-1]/a/text()')
print(result)
demo:
from lxml import etree
# 1\. 获取所有tr标签
# 2\. 获取第2个tr标签
# 3\. 获取所有class等于even的tr标签
# 4\. 获取所有a标签的href属性
# 5\. 获取所有的职位信息(纯文本)
parser = etree.HTMLParser(encoding='utf-8')
html = etree.parse("tencent.html",parser=parser)
# 1\. 获取所有tr标签
# //tr
# xpath函数返回的是一个列表
# trs = html.xpath("//tr")
# for tr in trs:
# print(etree.tostring(tr,encoding='utf-8').decode("utf-8"))
# 2\. 获取第2个tr标签
# tr = html.xpath("//tr[2]")[0]
# print(etree.tostring(tr,encoding='utf-8').decode("utf-8"))
# 3\. 获取所有class等于even的tr标签
# trs = html.xpath("//tr[@class='even']")
# for tr in trs:
# print(etree.tostring(tr,encoding='utf-8').decode("utf-8"))
# 4\. 获取所有a标签的href属性
# aList = html.xpath("//a/@href")
# for a in aList:
# print("http://hr.tencent.com/"+a)
# 5\. 获取所有的职位信息(纯文本)
trs = html.xpath("//tr[position()>1]")
positions = []
for tr in trs:
# 在某个标签下,再执行xpath函数,获取这个标签下的子孙元素
# 那么应该在//之前加一个点,代表是在当前元素下获取
href = tr.xpath(".//a/@href")[0]
fullurl = 'http://hr.tencent.com/' + href
title = tr.xpath("./td[1]//text()")[0]
category = tr.xpath("./td[2]/text()")[0]
nums = tr.xpath("./td[3]/text()")[0]
address = tr.xpath("./td[4]/text()")[0]
pubtime = tr.xpath("./td[5]/text()")[0]
position = {
'url': fullurl,
'title': title,
'category': category,
'nums': nums,
'address': address,
'pubtime': pubtime
}
positions.append(position)
print(positions)
总结:
-
使用
xpath
语法。应该使用Element.xpath
方法。来执行xpath的选择。示例代码如下:trs = html.xpath("//tr[position()>1]")
xpath函数
返回来的永远是一个列表。-
获取某个标签的属性:
href = html.xpath("//a/@href") # 获取a标签的href属性对应的值
-
获取文本,是通过
xpath
中的text()
函数。示例代码如下:address = tr.xpath("./td[4]/text()")[0]
-
在某个标签下,再执行xpath函数,获取这个标签下的子孙元素,那么应该在斜杠之前加一个点,代表是在当前元素下获取。示例代码如下:
address = tr.xpath("./td[4]/text()")[0]
-
网友评论