0
点赞
收藏
分享

微信扫一扫

Python模块之BeautifulSoup

kolibreath 2022-01-05 阅读 51

目录

一、安装导入

二、操作步骤

第1步 解析html源码

第2步 定位节点

第3步 定位标签

第4步 提取内容,并保存


一、安装导入

#安装模块
cmd-->>>pip install bs4
#导入模块
from bs4 import BeautifulSoup

二、操作步骤

第1步 解析html源码

#HTML源码
html = """
<html>
	<head>
		<title>BeautifulSoup技术</title>
	</head>
	<body>
	<p class="title"><b>静夜思</b></p>
	<p class="content">
		窗前明月光,<br />
		疑似地上霜。 <br />
		举头望明月,<br />
		低头思故乡。 <br />
	</p>
	<p class="other">
		李白(701年-762年),字太白,号青莲居士,又号“谪仙人”,
		唐代伟大的浪漫主义诗人,被后人誉为“诗仙”,与
		<a href="http://example.com/dufu" class="poet" id="link1">杜甫</a>
		并称为“李杜”,为了与另两位诗人
		<a href="http://example.com/lishangyin" class="poet" id="link2">李商隐</a>、
		<a href="http://example.com/dumu" class="poet" id="link3">杜牧</a>即“小李杜”区别,杜甫与李白又合称“大李杜”。
		其人爽朗大方,爱饮酒...
	</p>
	<p class="story">...</p>
"""

#解析网页源码
soup=BeautifulSoup(html)

第2步 定位节点

#定位节点
#可通过class、name、id等节点位置,来定位节点
#find()获取找到的第一个节点位置
tag=soup.find(class_='other')

#当class、name等有多个时,使用find_all来获取所有节点
#soup.find_all(class_='other')

搜索文档树常用find、find_all。

find_all()函数是可以接受参数进行指定节点查询,接受正则表达式作为参数,还可以接受多个参数。 

#接受参数
soup.find_all(id='link1')

#接受正则表达式
soup.find_all(re.compile('^b')) #定位所有以b开头的节点

#接受多个属性参数
soup.find_all('a',class_="poet")

第3步 定位标签

#在定位到的节点下,定位标签

#定位文本标签
text_tag=tag.find('p')
#定位链接标签
link=tag.find_all('a')

第4步 提取内容,并保存

#获取文本
text=text_tag.get_text()
#定位到的节点下直接是文本
text=tag.get_text()

#获取链接,保存到列表中
urllist=[]
for url in link:
    url=link.get('href')
    urllist.append(url)

参考文章:

[Python从零到壹] 五.网络爬虫之BeautifulSoup基础语法万字详解 

举报

相关推荐

0 条评论