一、xpath
xpath用于定位html中的元素。
/ 表示从根节点进行查找元素
// 从匹配的当前节点来对文档的节点进行选择
. 选取当前节点
.. 选取当前节点的父节点
@ 选择属性
/html 选取根节点下的所有html元素,也就是整个html文档。
/body/div 选取属于body的子元素中所有div元素。
//div 选取所有div标签的子元素,不管在html文档中的为止。
@class 选取名称为class的所有属性
通配符
* 匹配任何元素节点
@* 匹配任意属性
//* 选取文件中的所有元素。
//title[@*] 选取所有带有属性的title。
| 代表和的关系。
//body/div | //body/li 选取body元素的所有div元素和li元素
//div | // li 选取文档中所有的div 和li 元素。
二、beautifulsoap
beautifulsoap 是一个从html或者xml文件中提取数据的python库。
安装命令:
pip install beautifulsoap4
引用库
from bs4 import BeautifulSoap
html_url = "http://wwww.test.com/test.html"
html_file = open(html_url, "r", encoding="gbk")
html_handle = html_file.read()
soup = BeautifulSoap(html_handle, 'html.parser')
获取html文档头
print(soup.head)
获取节点中的属性
print(soup.p.attrs)
获取所有的p元素
ps = soup.find_all("p")
pring(ps)
通过id进行查找
result = soup.find_all(id="testid")
按照属性进行查找
jobs = soup.find_all("td", class_="jobs")
print(jobs)
其中td是元素标签,class_表示class属性