Python网络爬虫与信息提取-Day6-Beautiful Soup库

本文介绍了如何安装BeautifulSoup库并使用它来解析HTML文档。包括了从网页抓取HTML内容到解析HTML标签的方法,展示了如何提取标签名、属性及字符串。

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

安装Beautiful Soup库:

pip install beautifulsoup4

 

Beautiful Soup库的安装小测

演示HTML页面地址:http://python123.io/ws/demo.html

1.手工获得HTML源代码

打开浏览器,右键点击“查看源文件”

2.利用requests

import requests

r = requests.get(“http://python123.io/ws/demo.html”)

r.text

demo = r.text

 

Beautiful Soup库安装小测

from bs4 import BeautifulSoup
soup = BeautifulSoup(demo,“html.parser”)
print(soup.prettify())


from bs4 import BeautifulSoup
soup = BeautifulSoup(‘<p>data</p>’,“html.parser”)

Beautiful Soup库的基本元素

 

 HTML文件<==>标签树

<html>

    <body>

          <p class=“title”></p>

    </body>

</html>

Beautiful Soup库是解析、遍历、维护“标签树”的功能库

 

<p ></p>:标签Tag

<p class=“title”></p>

名称Name,成对出现

属性Attributes0个或多个

 

Beautiful Soup库,也叫beautifulsoup4bs4

约定引用方式如下,即主要是用BeautifulSoup

from bs4 import BeautifulSoup
import bs4

HTML文件<==>标签树<==>BeautifulSoup

>>> from bs4 import BeautifulSoup

>>> soup = BeautifulSoup("<html>data</html>","html.parser")

>>> soup2 = BeautifulSoup(open("D://demo.html"),"html.parser")

 

Beautiful Soup库解析器

soup = BeautifulSoup("<html>data</html>","html.parser")

解析器

使用方法

条件

bs4HTML解析器

BeautifulSoup(mk,'html.parser')

安装bs4

lxmlHTML解析器

BeautifulSoup(mk,'lxml')

pip install lxml

lxmlXML解析器

BeautifulSoup(mk,'xml')

pip install lxml

html5lib的解析器

BeautifulSoup(mk,'html5lib')

pip install html5lib


BeautifulSoup类的基本元素

(1)Tag 标签

最基本的信息组织单元,分别用<></>标明开头和结尾

任何存在于HTML语法中的标签都可以用soup.<tag>访问获得

HTML文档中存在多个相同<tag>对应内容时,soup.<tag>返回第一个

>>> from bs4 import BeautifulSoup

>>> soup = BeautifulSoup(demo,"html.parser")

>>> soup.title

<title>This is a python demo page</title>

>>> tag = soup.a

>>> tag

<a class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">Basic Python</a>

 

(2)Tagname(名字)

<p></p>的名字是'p',格式:<tag>.name

每个<tag>都有自己的名字,通过<tag>.name获取,字符串类型

>>> soup.a.name

'a'

>>> soup.a.parent.name

'p'

>>> soup.a.parent.parent.name

'body'

 

(3)Tagattrs(属性)

字典形式组织,格式:<tag>.attrs

一个<tag>可以有0或多个属性,字典类型

>>> tag = soup.a

>>> tag.attrs

{'href': 'http://www.icourse163.org/course/BIT-268001', 'class': ['py1'], 'id': 'link1'}

>>> tag.attrs['class']

['py1']

>>> tag.attrs['href']

'http://www.icourse163.org/course/BIT-268001'

>>> type(tag.attrs)

<class 'dict'>

>>> type(tag)

<class 'bs4.element.Tag'>

 

(4)TagNavigableString

标签内非属性字符串,<></>中字符串,格式:<tag>.string

>>> soup.a

<a class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">Basic Python</a>

>>> soup.a.string

'Basic Python'

>>> soup.p

<p class="title"><b>The demo python introduces several python courses.</b></p>

>>> soup.p.string

'The demo python introduces several python courses.'

>>> type(soup.p.string)

<class 'bs4.element.NavigableString'>

 

NavigableString可以跨越多个层次

 

(5)TagComment

标签内字符串的注释部分,一种特殊的Comment类型

>>> newsoup = BeautifulSoup("<b><!--This is a comment--></b><p>This is not a comment</p>","html.parser")

>>> newsoup.b.string

'This is a comment'

>>> type(newsoup.b.string)

<class 'bs4.element.Comment'>

>>> newsoup.p.string

'This is not a comment'

>>> type(newsoup.p.string)

<class 'bs4.element.NavigableString'>




<think>好的,用户想要一个Python爬虫的示例,特别是爬取名言网站的数据。我需要先理解他们的需求,可能他们刚开始学习爬虫,需要一个简单易懂的例子。 首先,我应该选择一个合适的。用户可能对Beautiful SoupScrapy都有兴趣,但根据引用内容,用户提到了beautifulsoup4的示例[^1],以及Scrapy的相关教程[^3][^4]。不过用户可能更倾向于一个简单的示例,所以先用Beautiful Soup可能更合适,因为它更易于入门。 接下来,确定目标网站。需要找一个稳定的、允许爬取的名言网站。比如quotes.toscrape.com,这个网站专门用于爬虫练习,结构简单,适合教学。 然后,编写代码步骤。首先安装所需的,比如requestsbeautifulsoup4。然后发送HTTP请求获取页面内容,解析HTML提取数据,最后存储数据。用户可能需要详细的代码注释,方便理解每一步的作用。 还要考虑异常处理,比如网络请求失败的情况,使用try-except块来捕获异常,提高代码的健壮性。此外,存储数据到CSV文件,方便后续处理,这也是常见的需求。 同时,用户可能对扩展功能感兴趣,比如定时抓取或使用Scrapy框架。根据引用[2][^4],可以提到使用schedule定时运行,或者用Scrapy构建更复杂的爬虫。这部分可以作为扩展内容,满足不同层次的需求。 需要确保代码符合Python最佳实践,比如使用with语句处理文件,合理组织代码结构。另外,检查是否需要遵守目标网站的robots.txt,确保合法合规。 最后,生成相关问题,帮助用户深入学习解决可能遇到的困难。比如性能优化、反爬虫策略处理,以及数据存储的其他方式等。 总结,用户需要一个清晰、可运行的示例,以及相关的扩展知识,帮助他们从基础到进阶逐步学习Python爬虫技术。</think>以下是使用PythonBeautifulSoupRequests实现名言网站数据爬取的示例,基于引用内容中的技术点进行说明[^1]: ### 基础版示例(使用BeautifulSoup) ```python import requests from bs4 import BeautifulSoup import csv def scrape_quotes(): url = "http://quotes.toscrape.com" try: response = requests.get(url) response.encoding = 'utf-8' soup = BeautifulSoup(response.text, 'html.parser') quotes = [] for quote in soup.find_all('div', class_='quote'): text = quote.find('span', class_='text').text author = quote.find('small', class_='author').text tags = [tag.text for tag in quote.find_all('a', class_='tag')] quotes.append({ 'text': text, 'author': author, 'tags': ', '.join(tags) }) # 保存到CSV with open('quotes.csv', 'w', newline='', encoding='utf-8') as f: writer = csv.DictWriter(f, fieldnames=['text', 'author', 'tags']) writer.writeheader() writer.writerows(quotes) print(f"成功爬取{len(quotes)}条数据") except Exception as e: print(f"爬取失败: {str(e)}") if __name__ == "__main__": scrape_quotes() ``` ### 功能说明 1. **数据采集**:通过`requests`获取网页内容,使用`BeautifulSoup`解析HTML 2. **元素定位**:根据CSS类名定位名言文本(`.text`)、作者(`.author`)标签(`.tag`) 3. **数据存储**:将结果保存为CSV文件,包含字段:名言内容、作者、标签 ### 扩展版建议(使用Scrapy框架) 根据引用[3],对于大规模爬取建议使用Scrapy框架: ```python import scrapy class QuotesSpider(scrapy.Spider): name = "quotes" start_urls = ['http://quotes.toscrape.com'] def parse(self, response): for quote in response.css('div.quote'): yield { 'text': quote.css('span.text::text').get(), 'author': quote.css('small.author::text').get(), 'tags': quote.css('div.tags a.tag::text').getall() } next_page = response.css('li.next a::attr(href)').get() if next_page: yield response.follow(next_page, self.parse) ``` ### 定时执行方案(基于引用[2][^2]) ```python import schedule import time from scrapy.crawler import CrawlerProcess from scrapy.utils.project import get_project_settings def run_spider(): process = CrawlerProcess(get_project_settings()) process.crawl(QuotesSpider) process.start() schedule.every().day.at("09:00").do(run_spider) while True: schedule.run_pending() time.sleep(60) ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值