117 字
1 分钟
python中网页解析库及基本用法
lxml
安装
pip install lxml基本使用
from lxml import etree html = etree.HTML(text) res = html.xpath(xpath_string)限制属性:
'//div[@class="attr0"]'获取文本:
'//div/text()'获取属性:
‘//li/a/@href’
Beautifal Soup
安装
pip install beautifulsoup4
基本使用
from bs4 import BeautifulSoup soup = BeautifulSoup(html, 'lxml') for i, child in enumerate(soup.children): print(i, child)获取属性:
soup.p.attrs['name']获取文本:
soup.p.tring(默认为当前节点下的第一个p节点)
方法选择器find_all(name, attrs, recursive, text), find类似但返回单个
- 查找所有
ul节点:soup.find_all(name='ul') - 加入属性:
soup.find_all(name='ul', attrs={'id':'demo1'})
- 查找所有

