python爬虫 -04- lxml和xpath的简单使用

xpath语法

表达式描述
nodename选取此节点的所有子节点。
/从根节点选取。
//从匹配选择的当前节点选择文档中的节点,而不考虑它们的位置。
.选取当前节点。
选取当前节点的父节点。
@选取属性。
following-sibling::span[1]附近的节点

lxml使用

from bs4 import BeautifulSoup
from lxml import etree
import doc_html

soup = BeautifulSoup(doc_html.html_doc, "lxml")
print(soup.input)

print("----------------------------------华丽的分割线--------------------------------------------")

selector = etree.HTML(doc_html.html_doc)
# 取出所有的链接
links = selector.xpath("//div[@class='first-2']/a/@href")
for link in links:
    print(link)

a_ = selector.xpath("//div[@class='first-2']/a")
print(a_)
text = a_[0].xpath("../h2/text()")
print(text)


# 第一个
print(selector.xpath("//select/option[1]/text()"))
# 到处第一个
print(selector.xpath("//select/option[last()]/text()"))
# 到处第二个
print(selector.xpath("//select/option[last()-1]/text()"))
# 前两个
print(selector.xpath("//select/option[position()<3]/text()"))
# 指定标签内部情况和样式名
print(selector.xpath("//table/tr[td>21]/td[@class='age info']/@class"))
# 多样式名
print(selector.xpath("//table/tr/td[contains(@class, 'age info') and contains(@id, 'age')]/text()"))

 输出

<input style="background-color: transparent; border:0px;" type="text"/>
----------------------------------华丽的分割线--------------------------------------------
http://baidu.com
https://blog.csdn.net/
[<Element a at 0x14c3fb8e480>, <Element a at 0x14c3fb8e500>]
['这里可能用来有透明色']
['信息学院']
['药学院']
['体育学院']
['信息学院', '护理学院']
['age info', 'age info', 'age info']
['21']

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值