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']