博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Beautifulsoup的使用
阅读量:5917 次
发布时间:2019-06-19

本文共 2014 字,大约阅读时间需要 6 分钟。

from bs4 import BeautifulSoup# html_doc = """# The Dormouse's story# ### 

Once upon a time there were three little sisters; and their names were# Elsie,# Lacie and# Tillie;# and they lived at the bottom of a well.

##

...

# """# soup=BeautifulSoup(html_doc,'lxml')# print(soup) #会将不完整的html文本补充完成# print(soup.prettify()) #将html文本进行结构划分# print(soup.p.b) #查找文本的第一个标签

The Dormouse's story

#查找子孙节点# print(list(soup.p.descendants))# print(soup.p.a.text) #显示标签内的文本# print(soup.p.children) #
,迭代器使用list()转为列表形式# print(list(soup.p.children)) #['Once upon a time there were three little sisters; and their names were\n',
Elsie, ',\n',
Lacie, ' and\n',
Tillie, ';\nand they lived at the bottom of a well.']# print(soup.p.contents)# print(soup.a.parent) #查找标签a的父标签,包括子标签和内容# print(soup.a.parents) #
# print(list(soup.a.parents)) #结果类型为列表,查找所有父标签包括父标签的内容,直到document

find和findall

html_doc = """The Dormouse's story

The Dormouse's story

Once upon a time there were three little sisters; and their names wereElsie,Lacie andTillie;and they lived at the bottom of a well.

...

"""soup=BeautifulSoup(html_doc,'lxml')# print(soup.find_all('a')) #[Elsie, Lacie, Tillie]# print(soup.find_all('a',id='link2')) #[Lacie]# print(soup.find('a',id='link2')) #Lacie# print(soup.find(id='link2').attrs['href']) #http://example.C/lacie# print(soup.find_all(attrs={'class':'sister'})) #[Elsie, Lacie, Tillie]# print(soup.find('p').find('b')) #The Dormouse's story

CSS选择器

from bs4 import BeautifulSouphtml_doc = """The Dormouse's story

The Dormouse's story

Once upon a time there were three little sisters; and their names wereElsie,Lacie andTillie;and they lived at the bottom of a well.

...

"""soup=BeautifulSoup(html_doc,'lxml')# print(soup.select('p b')) #[The Dormouse's story] 查找p标签下的b标签# print(soup.select('p')[1].select('#link2')[0].attrs['href']) #http://example.com/lacie 获取标签的属性# print(soup.select('p')[1].get_text()) #获取标签的文本内容

 

转载于:https://www.cnblogs.com/c491873412/p/7816067.html

你可能感兴趣的文章
深入理解Solidity之源文件及合约结构——Solidity中文文档(4)
查看>>
拥抱大健康,瞄准第一股
查看>>
pyhanlp 停用词与用户自定义词典功能详解
查看>>
比特币交易费用创新低的背后:交易量下降了68%
查看>>
前端自动化构建工具webpack简单入门——2
查看>>
MySQL面试题--常见的四种隔离级别
查看>>
Python中的循环退出举例及while循环举例
查看>>
企业级 SpringBoot 教程 (一)构建第一个SpringBoot工程
查看>>
玩转大数据系列之一:数据采集与同步
查看>>
Knative Tracing 介绍
查看>>
Nacos 入门(一)
查看>>
hikari druid c3p0 dbcp jdbc对比
查看>>
OSChina 周一乱弹 —— 可惜不是富二代
查看>>
OSChina 周五乱弹 ——论HR的日常心塞
查看>>
OSChina 周四乱弹 ——我也得了晚上睡不着白天睡不醒症!
查看>>
燃烧的CPU
查看>>
使用基于共享内存的自旋锁在虚拟机间进行同步的可行性研究
查看>>
这周心情起伏有点大。。。
查看>>
安装sysbench
查看>>
crunch 練習
查看>>