Python中BeautifulSoup的基础用法--附实例

本文介绍使用Python的requests和BeautifulSoup库抓取豆瓣网站上的畅销小说排名。从获取网页源码到解析HTML,详细展示了如何定位并提取前四名小说的名称。

前言

安装好了BeautifulSoup库

一、requests库的简单使用

通过requests库提供的方法获取要爬取页面的数据,并把数据传递给一个变量供后续操作,requests的简单使用方法如下:

# coding = utf-8
import requests

rq = requests.get("https://www.baidu.com").text
print(rq)

打印出来的结果就是百度首页的页面源码

二、BeautifulSoup 的使用

下面通过一个实例来说明其使用方法----爬取douban的畅销小说

(1) 首先通过requests获取网页源码
# coding = utf-8
import requests
from bs4 import BeautifulSoup

rq = requests.get("https://www.douban.com/tag/%E5%B0%8F%E8%AF%B4/?focus=book")

# 获取页面的源码--text文本方式
content = rq.text
	
(2)通过BeautifulSoup创造一个实例
# coding = utf-8
import requests
from bs4 import BeautifulSoup

rq = requests.get("https://www.douban.com/tag/%E5%B0%8F%E8%AF%B4/?focus=book")

# 获取页面的源码--text文本方式
content = rq.text

soup = BeautifulSoup(content, "html.parser")
(3) BeautifulSoup提供的一些方法

soup 就是BeautifulSoup处理格式化后的字符串,soup.title 得到的是title标签soup.p 得到的是文档中的第一个p标签,要想得到所有标签,得用find_all函数。find_all 函数返回的是一个序列,可以对它进行循环,依次得到想到的东西.
get_text() 是返回文本,这个对每一个BeautifulSoup处理后的对象得到的标签都是生效的。你可以试试 print soup.p.get_text()其实是可以获得标签的其他属性的,比如我要获得a标签的href属性的值,可以使用 print soup.a[‘href’],类似的其他属性,比如class也是可以这么得到的(soup.a[‘class’])。
特别的,一些特殊的标签,比如head标签,是可以通过soup.head 得到。如何获得标签的内容数组?使用contents 属性就可以 比如使用 print soup.head.contents,就获得了head下的所有子孩子,以列表的形式返回结果,可以使用 [num] 的形式获得 ,获得标签,使用.name 就可以。

(4)使用BeautifulSoup提供的方法处理soup,获取豆瓣排名前4的小说
# coding = utf-8
import requests
from bs4 import BeautifulSoup

rq = requests.get("https://www.douban.com/tag/%E5%B0%8F%E8%AF%B4/?focus=book")

# 获取页面的源码--text文本方式
content = rq.text

soup = BeautifulSoup(content, "html.parser")

# 通过find 方法找到id = "book"的div
book_div = soup.find("div", attrs = "{"id": "book"}")

#在找到的book_div中通过find_all找到块下的其他标签
fiction = book_div.find_all("a", attrs{"class": "title"}, limit = 4)

# 找到前4 的小说后获取其名字
limit_novel = fiction.string

得到的结果如下:

"C:\Program Files\Python37\python.exe" C:/PythonLearn/Crawl/BeautifulLearn.py
活着
追风筝的人
小王子
百年孤独

Process finished with exit code 0

注意:

<div class="postContent">
    <p><div id="picture">
	<p>
		<img alt="哎呀,住嘴,第1张" src="http://pic.topmeizi.com/wp-content/uploads/2017a/04/06/01.jpg" /><br />
		<img alt="哎呀,住嘴,第2张" src="http://pic.topmeizi.com/wp-content/uploads/2017a/04/06/02.jpg" /><br />
		<img alt="哎呀,住嘴,第3张" src="http://pic.topmeizi.com/wp-content/uploads/2017a/04/06/03.jpg" /><br />
		<img alt="哎呀,住嘴,第4张" src="http://pic.topmeizi.com/wp-content/uploads/2017a/04/06/04.jpg" /><br />
		<img alt="哎呀,住嘴,第5张" src="http://pic.topmeizi.com/wp-content/uploads/2017a/04/06/05.jpg" /><br />
		<img alt="哎呀,住嘴,第6张" src="http://pic.topmeizi.com/wp-content/uploads/2017a/04/06/06.jpg" /><br />
		<img alt="哎呀,住嘴,第7张" src="http://pic.topmeizi.com/wp-content/uploads/2017a/04/06/07.jpg" /><br />
		<img alt="哎呀,住嘴,第8张" src="http://pic.topmeizi.com/wp-content/uploads/2017a/04/06/08.jpg" /><br />
		<img alt="哎呀,住嘴,第9张" src="http://pic.topmeizi.com/wp-content/uploads/2017a/04/06/09.jpg" /></p>
</div>

类似于入上这种网页的下载地址的获取,可以通过如下方式

  1. 通过find先找到div 满足 id=‘picture’ 的第一个匹配(如果需要找的div不是第一个,那么也可以用find_all找到之后进行筛选),第一轮筛选之后,
    查找的代码:
target_position = soup.find('div', id='picture')

结果应该如下:

<div id="picture">
<p>
<img alt="哎呀,住嘴,第1张" src="http://pic.topmeizi.com/wp-content/uploads/2017a/04/06/01.jpg"/><br/>
<img alt="哎呀,住嘴,第2张" src="http://pic.topmeizi.com/wp-content/uploads/2017a/04/06/02.jpg"/><br/>
<img alt="哎呀,住嘴,第3张" src="http://pic.topmeizi.com/wp-content/uploads/2017a/04/06/03.jpg"/><br/>
<img alt="哎呀,住嘴,第4张" src="http://pic.topmeizi.com/wp-content/uploads/2017a/04/06/04.jpg"/><br/>
<img alt="哎呀,住嘴,第5张" src="http://pic.topmeizi.com/wp-content/uploads/2017a/04/06/05.jpg"/><br/>
<img alt="哎呀,住嘴,第6张" src="http://pic.topmeizi.com/wp-content/uploads/2017a/04/06/06.jpg"/><br/>
<img alt="哎呀,住嘴,第7张" src="http://pic.topmeizi.com/wp-content/uploads/2017a/04/06/07.jpg"/><br/>
<img alt="哎呀,住嘴,第8张" src="http://pic.topmeizi.com/wp-content/uploads/2017a/04/06/08.jpg"/><br/>
<img alt="哎呀,住嘴,第9张" src="http://pic.topmeizi.com/wp-content/uploads/2017a/04/06/09.jpg"/></p>
</div>

2.可知已经筛选出了div 满足id='picture’的内容,我们想要的内容是对应的下载地址,那么我们还需要通过img标签来筛选,因为img标签有很多个,所以我们在第一轮find的结果中用find_all来查找
查找代码如下:

target_position = soup.find('div', id='picture').find_all('img')

查询的结果是一个列表,其中包含了所有img的内容,通过查看其类型得出属于 <class ‘bs4.element.ResultSet’> ,所以可以通过BeautifulSoup的属性取值方式来取得下载地址
3.比如取第一个的下载地址,代码如下:

target_position = soup.find('div', id='picture').find_all('img')[0]['src']

结果就是 http://pic.topmeizi.com/wp-content/uploads/2017a/04/06/01.jpg 这个下载地址咯

<think>好的,用户想了解如何在Python中使用BeautifulSoup进行网页解析。首先,我需要回忆BeautifulSoup的基本用法和相关步骤。根据用户提供的引用内容,安装部分已经提到用pip安装beautifulsoup4,所以第一步应该确认安装步骤,可能还要提到需要安装解析器如lxml或html.parser。 接下来是导入库的部分,用户提供的引用1中提到了引入BeautifulSoup,所以需要说明正确的导入方式。然后是实例BeautifulSoup对象,这里可能需要演示如何将HTML内容或文件加载到BeautifulSoup中,比如使用requests获取网页内容后再解析。 然后需要介绍常用的方法,比如find()、find_all()、select()等,以及如何根据标签名、类名、ID等查找元素。用户提到的引用3中提到了数据提取,这部分可能需要详细说明如何提取文本、属性等内容。 还需要注意不同的解析器之间的区别,比如lxml和html.parser的性能差异,确保用户了解选择合适的解析器的重要性。此外,可能还需要提到常见的问题处理,比如编码问题或处理不规范的HTML。 用户可能对实际应用场景感兴趣,所以最好给出一个具体的例子,比如解析某个网页的结构,提取标题、链接等信息。同时,要确保代码示例正确,语法无误,并且符合用户提供的LaTeX格式要求,但在这个问题中可能不需要数学公式,所以主要关注代码块和文本结构。 最后,生成相关问题时,要考虑用户可能进一步想了解的内容,比如高级用法、异常处理、与其他库的结合使用等。确保问题覆盖用户可能遇到的后续疑问。</think>在Python中使用BeautifulSoup进行网页解析主要包括以下步骤: ### 一、安装与导入 1. 安装库(需额外安装解析器): ```bash pip install beautifulsoup4 lxml # 推荐安装lxml解析器[^2] ``` 2. 导入库: ```python from bs4 import BeautifulSoup import requests # 用于获取网页内容 ``` ### 二、基础解析流程 1. **获取网页内容** ```python url = 'https://example.com' response = requests.get(url) html_content = response.text ``` 2. **创建解析对象** ```python soup = BeautifulSoup(html_content, 'lxml') # 指定lxml解析器[^1] # 或使用内置解析器 # soup = BeautifulSoup(html_content, 'html.parser') ``` ### 三、核心数据提取方法 1. **标签定位** ```python # 获取首个<div>标签 div_tag = soup.find('div') # 获取所有<p>标签 all_p = soup.find_all('p') # CSS选择器定位 articles = soup.select('div.article > h2.title') ``` 2. **属性提取** ```python # 获取标签内文本 title_text = soup.title.string # 提取属性值 link = soup.a['href'] # 获取全部属性 img_attrs = soup.img.attrs ``` 3. **层级遍历** ```python # 父节点 parent = div_tag.parent # 子节点遍历 for child in div_tag.children: print(child) # 兄弟节点 next_sibling = div_tag.next_sibling ``` ### 四、完整示例(解析新闻标题) ```python url = 'https://news.example.com' response = requests.get(url) soup = BeautifulSoup(response.text, 'lxml') # 提取所有新闻标题 news_list = [] for article in soup.select('div.news-item'): title = article.find('h2', class_='title').text.strip() time = article.find('span', class_='time')['datetime'] news_list.append({'title': title, 'time': time}) ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值