python的网页解析器_网页解析器(BeautifulSoup)-- Python

分享一下关于 Python的网页解析器(BeautifulSoup)

BeautifulSoup解析器

为了实现解析器,可以选择使用正则表达式、html.parser、BeautifulSoup、lxml等,所以BeautifulSoup是比较好的选择。

其中,正则表达式基于模糊匹配,而另外三种则是基于DOM结构化解析。

安装测试

1、安装,在命令行下执行pip install beautifulsoup4。

2、测试

importbs4print(bs4)

使用说明

beautifulsoup.jpg

beautifulsoup2.jpg

基本用法

1、创建BeautifulSoup对象

import bs4

from bs4 import BeautifulSoup

# 根据html网页字符串创建BeautifulSoup对象

html_doc = """

The Dormouse's story

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)

print(soup.prettify())

2、访问节点

print(soup.title)

print(soup.title.name)

print(soup.title.string)

print(soup.title.parent.name)

print(soup.p)

print(soup.p['class'])

3、指定tag、class或id

print(soup.find_all('a'))

print(soup.find('a'))

print(soup.find(class_='title'))

print(soup.find(id="link3"))

print(soup.find('p',class_='title'))

4、从文档中找到所有标签的链接

for link in soup.find_all('a'):

print(link.get('href'))

warning.jpg

出现了警告,根据提示,我们在创建BeautifulSoup对象时,指定解析器即可。

soup = BeautifulSoup(html_doc,'html.parser')

5、从文档中获取所有文字内容

print(soup.get_text())

6、正则匹配

link_node = soup.find('a',href=re.compile(r"til"))

print(link_node)

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值