python爬虫笔记:BeautifulSoup用法

给出一段html

html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><b>The Dormouse's story</b></p>
<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>
<p class="story">...</p>
"""

解析html

from bs4 import BeautifulSoup
soup = BeautifulSoup(html_doc, "html.parser")

获得标题的结构

print(soup.title)
print(soup.title.name)
print(soup.title.string)	# 获取标签内部的具体文字
output:
<title>The Dormouse's story</title>
title
The Dormouse's story
print(soup.p)
output:
<p class="title"><b>The Dormouse's story</b></p>

查看标签的所以属性:
所有属性都可以打出来,是一个字典类型

print(soup.a.attrs)
output:
{'href': 'http://example.com/elsie', 'class': ['sister'], 'id': 'link1'}
print(soup.a['href'])	# 查看某个具体属性
print(soup.a.get('href')) # 通过get()函数查看具体属性
output:
http://example.com/elsie
http://example.com/elsie
soup.p['class']="new story"   # 修改某个具体属性
del soup.p['class']   # 删除某个具体属性

find_all可以查找所以包含对应内容的结构,返回的是一个list

print(soup.find_all('a')) # 寻找所以包含a的结构
结果为:
[<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>,
<a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]

find 函数:
find(name, attrs, recursive, text, **wargs) # recursive 递归的,循环的
这些参数相当于过滤器一样可以进行筛选处理。不同的参数过滤可以应用到以下情况:

  1. 查找标签,基于name参数
  2. 查找文本,基于text参数
  3. 基于正则表达式的查找
  4. 查找标签的属性,基于attrs参数
  5. 基于函数的查找
print(soup.find(id='link3')
print(soup.find('p', class_='title'))
print(soup.find(attrs={'class': 'title'}))
结果为:
<a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>
<p class="title"><b>The Dormouse's story</b></p>
<p class="title"><b>The Dormouse's story</b></p>
print(soup.get_text())
结果为:
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.
...
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

御风之

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值