beautifulSoup20%基础知识

本文介绍如何使用BeautifulSoup解析HTML文档,包括创建对象、访问节点、遍历文档树及使用CSS选择器筛选元素。通过实例演示了如何获取标签、字符串、属性及进行高级查询。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

详细的内容请看这里——参考博客,下面是自己需要参考的部分总结。

  1. 创建 Beautiful Soup 对象,首先必须要导入 bs4 库
from bs4 import BeautifulSoup
  1. 创建一个字符串,请将字符串拷贝出来,再参考后面的例子,这样才能明白。
html = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title" name="dromouse"><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>
"""
  1. 创建 beautifulsoup 对象
soup = BeautifulSoup(html)
  1. Beautiful Soup将复杂HTML文档转换成一个复杂的树形结构,每个节点都是Python对象,所有对象可以归纳为4种:Tag、NavigableString、BeautifulSoup、Comment。

(1) Tag:Tag 是什么?通俗点讲就是 HTML 中的一个个标签,例如head,title,a,p等,注释为输出。

print soup.title
#<title>The Dormouse's story</title>
print soup.head
#<head><title>The Dormouse's story</title></head>
print soup.a
#<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>
print soup.p
#<p class="title" name="dromouse"><b>The Dormouse's story</b></p>

它有两个属性,name和attrs,使用如下。

#name到没什么,主要在sttrs。
print soup.name #[document]
print soup.head.name #head

print soup.p.attrs
#{'class': ['title'], 'name': 'dromouse'}
print soup.p['class'] #['title']

(2)NavigableString:获取标签内的字符串。

print soup.p.string
#The Dormouse's story

(3)BeautifulSoup:
(4)Comment

  1. 遍历文档树,.contents .children 属性。
print soup.head.contents 
#[<title>The Dormouse's story</title>]
print soup.head.contents[0]#会以列表的形式出书。
#<title>The Dormouse's story</title>
  1. CSS选择器,我们在写 CSS 时,标签名不加任何修饰,类名前加点,id名前加 #,在这里我们也可以利用类似的方法来筛选元素,用到的方法是 soup.select(),返回类型是 list。
print soup.select('title') 
#[<title>The Dormouse's story</title>]
print soup.select('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>]

print soup.select('.sister')#通过类名查找
#[<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>]

print soup.select('#link1')#通过id查找
#[<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>]

#组合查找,二者需要用空格分开
print soup.select('p #link1')
#[<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>]
print soup.select("head > title")
#[<title>The Dormouse's story</title>]

#属性查找,属性需要用中括号括起来,注意属性和标签属于同一节点,所以中间不能加空格,
print soup.select('p a[href="http://example.com/elsie"]')
#[<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>]

<think>嗯,用户想学习BeautifulSoup相关的爬虫基础知识,特别是基础教程和使用方法。首先,我需要整理BeautifulSoup的核心知识点,确保涵盖安装、基本对象、解析器选择以及常用方法。 首先,安装部分。用户可能需要知道如何安装BeautifulSoup和依赖库,比如用pip安装bs4和requests。记得提醒安装解析器,比如lxml或html5lib,因为不同的解析器有不同的优缺点。 接下来是基本对象。根据引用[4],BeautifulSoup有四种对象:Tag、NavigableString、BeautifulSoup和Comment。需要逐一解释这些对象是什么,并给出例子,比如如何获取Tag的名称和属性。 然后,解析器的选择很重要。不同的解析器在速度和兼容性上有差异,比如lxml通常更快,而html5lib能处理复杂的HTML。用户可能需要根据项目需求选择合适的解析器。 常用方法部分,要包括如何加载文档,比如用requests获取网页后用BeautifulSoup解析。然后,find和find_all的区别,以及CSS选择器的使用。这些是爬虫中最常用的方法,需要详细说明并给出代码示例,比如如何提取标题或链接。 另外,用户可能对实际案例感兴趣,引用[2]提到结合Requests库爬取新闻网站的信息。可以举一个简单的例子,比如爬取新闻标题和链接,这样用户能更好地理解应用过程。 最后,生成相关问题时要覆盖安装、对象、解析器、方法和应用场景,这样用户如果有进一步的问题,可以自行探索。同时,注意引用标记的正确使用,比如引用[1]和[2]对应的内容。 需要确保回答结构清晰,分步骤讲解,代码示例正确,并且语言简洁。避免使用复杂术语,让初学者也能理解。同时检查LaTeX格式是否正确,虽然这里可能用不到数学公式,但如果有变量或代码内嵌,仍需遵循规范。</think># BeautifulSoup 爬虫基础教程 ## 一、环境配置与安装 1. 安装核心库: ```bash pip install beautifulsoup4 requests ``` 2. 选择解析器(必须至少安装一个): - `lxml`(推荐):`pip install lxml` - `html5lib`:`pip install html5lib` > 注意:不同解析器对HTML容错处理能力不同[^1] ## 二、四大核心对象 1. **Tag对象** 对应HTML标签,可通过`.tagName`访问: ```python soup = BeautifulSoup(html_doc, 'lxml') title_tag = soup.title # 获取<title>标签 ``` 2. **NavigableString** 表示标签内的文本内容: ```python print(title_tag.string) # 输出标签内纯文本 ``` 3. **BeautifulSoup对象** 整个文档树的根节点: ```python print(type(soup)) # <class 'bs4.BeautifulSoup'> ``` 4. **Comment对象** 处理HTML注释的特殊类型: ```python comment = soup.b.string if type(comment) == bs4.element.Comment: print("这是注释内容") ``` ## 三、解析器对比 | 解析器 | 速度 | 依赖项 | 特性 | |--------------|--------|----------|--------------------------| | Python标准库 | 慢 | 无 | 容错性差 | | lxml | 快 | 需要C库 | 处理不规范HTML | | html5lib | 最慢 | 纯Python | 完全遵循HTML5标准 | ## 四、常用方法详解 ### 1. 文档加载 ```python import requests from bs4 import BeautifulSoup url = 'http://example.com' response = requests.get(url) soup = BeautifulSoup(response.text, 'lxml') # 推荐组合 ``` ### 2. 节点查找 **find() vs find_all()** ```python # 查找第一个<div> first_div = soup.find('div', class_='header') # 查找所有带href属性的<a>标签 all_links = soup.find_all('a', href=True) ``` **CSS选择器** ```python # 选择id为content的div下的所有p标签 paragraphs = soup.select('div#content > p') ``` ### 3. 属性提取 ```python for link in all_links: print(link['href']) # 获取href属性 print(link.get_text()) # 获取标签内全部文本 ``` ## 五、实战案例:新闻爬虫 ```python import requests from bs4 import BeautifulSoup url = 'https://news.example.com' response = requests.get(url) soup = BeautifulSoup(response.text, 'lxml') news_list = [] for article in soup.select('.news-article'): title = article.find('h2').get_text(strip=True) link = article.find('a')['href'] time = article.find('time')['datetime'] news_list.append({ '标题': title, '链接': link, '时间': time }) ``` > 该案例展示了如何提取结构化数据[^2] §§ 相关问题 §§ 1. 如何处理BeautifulSoup中的动态加载内容? 2. 如何防范反爬机制对BeautifulSoup的影响? 3. 如何将BeautifulSoup与Selenium结合使用? 4. 如何优化BeautifulSoup的解析效率? 5. 如何处理网页中的编码问题? : https://beautifulsoup.readthedocs.io/zh_CN/v4.4.0/ : https://example.com/crawler-case
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值