python爬虫_bs4(BeautifulSoup4)+find/find_all的Tag综合使用实例

时间:2025-02-11 17:04:55

bs4库的目的是解析resquest的text数据

import requests
# 引入BS库,下面的bs4就是beautifulsoup4
from bs4 import BeautifulSoup
url=
res = requests.get(url)
# 把网页解析为BeautifulSoup对象
soup = BeautifulSoup(res.text,'')
#soup是网页的源码

soup有两类方法find()与find_all()以及Tag对象
Tag什么要搞清楚
Tag一定不是数组,Tag一定不是数组,Tag一定不是数组

方法 作用
()或Tag,fingd_all() 提取Tag中的Tag
提取Tag中的文字
Tag[‘姓名’] 输入参数:属性名,可以提取Tag中这个属性的值
item = soup.find('div') #使用find()方法提取首个<div>元素,并放到变量item里。
items = soup.find_all('div')#用find_all()把所有符合要求的数据提取出来,并放在变量items里
#Tag对象只有find_all方法之后才能用
for item in items:           # 遍历列表items
    kind = item.find('h2')   # 在列表中的每个元素里,匹配标签<h2>提取出数据
    title = item.find(class_='title')  #  在列表中的每个元素里,匹配属性class_='title'提取出数据
    brief = item.find(class_='info') # 在列表中的每个元素里,匹配属性class_='info'提取出数据
    print(kind.text,'\n',title.text,'\n',title['href'],'\n',brief.text) # 打印书籍的类型、名字、链接和简介的文字
    

补充资料

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>练习用的网页</title>
        <style>
        a {
            text-decoration: none;
        }

        body {
            margin: 0;
            width:100%;
            height: 100%;
        }

        #header {
            background-color:#0c1f27;
            color:#20b2aa;
            text-align:center;
            padding:15px;
        }
        
        #nav {
            line-height:60px;
            background-color:#e0f2f0;
            width:80px;
            padding:30px;
            position: absolute;
            left: 0;
            top:0;
            bottom: 0;
        }

        #footer {
            background-color:#0c1f27;
            color:#20b2aa;
            clear:both;
            text-align:center;
            padding:35px;
        }

        #main {
            margin-left: 140px;
            padding-left: 150px;
            padding-right: 220px;
            overflow: scroll;
        }

        #article {
            display: flex;
            position: relative;
        }

        .catlog{
            font-size:20px;
            color:black;
            font-family: sans-serif;
        }

        .title {
            color:#20b2aa;
            font-size:20px;
        }

        .img {
            width: 185px;
            height: 266px;
        }
        </style>
    </head>

    <body>
        <div id="header">
        <h1 style="font-size:50px;">这个书苑不太冷</h1>
        </div>

        <div id="article">
            <div id="nav">
                <a href="#type1" class="catlog">科幻小说</a><br>
                <a href="#type2" class="catlog">人文读物</a><br>
                <a href="#type3" class="catlog">技术参考</a><br>
            </div>
            <div id="main">
                <div class="books">
                    <h2><a name="type1">科幻小说</a></h2>
                    <a href="/subject/27077140/" class="title">《奇点遗民》</a>
                    <p class="info">本书精选收录了刘宇昆的科幻佳作共22篇。《奇点遗民》融入了科幻艺术吸引人的几大元素:数字化生命、影像化记忆、人工智能、外星访客……刘宇昆的独特之处在于,他写的不是科幻探险或英雄奇幻,而是数据时代里每个人的生活和情感变化。透过这本书,我们看到的不仅是未来还有当下。</p> 
                    <img class="img" src="/view/subject/l/public/">
                    <br/>
                    <br/>
                    <hr size="1">
                </div>
                <div class="books">
                    <h2><a name="type2">人文读物</a></h2>
                    <a href="/subject/26943161/" class="title">《未来简史》</a>
                    <p class="info">未来,人类将面临着三大问题:生物本身就是算法,生命是不断处理数据的过程;意识与智能的分离;拥有大数据积累的外部环境将比我们自己更了解自己。如何看待这三大问题,以及如何采取应对措施,将直接影响着人类未来的发展。</p> 
                    <img class="img" src="/view/subject/l/public/">
                    <br/>
                    <br/>
                    <hr size="1">
                </div>
                
                <div class="books">
                    <h2><a name="type3">技术参考</a></h2>
                    <a href="/subject/25779298/" class="title">《利用Python进行数据分析》</a>
                    <p class="info">本书含有大量的实践案例,你将学会如何利用各种Python库(包括NumPy、pandas、matplotlib以及IPython等)高效地解决各式各样的数据分析问题。由于作者Wes McKinney是pandas库的主要作者,所以本书也可以作为利用Python实现数据密集型应用的科学计算实践指南。本书适合刚刚接触Python的分析人员以及刚刚接触科学计算的Python程序员。</p> 
                    <img class="img" src="ttps:///view/subject/l/public/">
                    <br/>
                    <br/>
                    <hr size="1">
                </div>
            </div>
        </div>

        <div id="footer">goood
        </div>
    </body>
</html>
HTML的基础结构
<html>
		<head>
				网页头的内容
		</head>
		<body>
				网页的具体内容
		</body>
</html>

HTML元素
<h1>		</h1>		一级标题
<h2>		</h2>		二级标题
<p>		</p>			段落
<a>		</a>			超级链接
<div>		</div>		块

HTML属性
class		为html元素第一一个或多个类
id		定义元素的唯一id
href		用来定义连接
style		规定元素行内样式

简单爬出解析实例

from bs4 import BeautifulSoup
import requests 
url='/all-about-the-future_04/'
response=requests.get(url)
content=response.text
soup=BeautifulSoup(content,'')

soup_task=soup.find_all(id='comments')
#print(soup_task[0])
pinlun=soup_task[0].find_all(class_="comment-list")
result=[]
a=pinlun[0].find_all('p')
for a1 in a:
    result.append(a1.text)
print(result)

'''调试笔记
print()
print(len())
print(x[0])
'''

实例3

from bs4 import BeautifulSoup
import requests 
url='/'
response=requests.get(url)
content=response.text
soup=BeautifulSoup(content,'')

result=soup.find_all('header',class_="entry-header")
print(len(result))
res=[]
for a in result:
    title=a.find('h2').text
    time=a.find('time',class_="updated").text
    url=a.find('a')['href']
    print('标题:'+title+'\n'+'更新时间:'+str(time)+'\n'+'网址:'+url+'\n')