码迷,mamicode.com
首页 > 其他好文 > 详细

BeautifulSoup之select find和find_all

时间:2018-02-05 00:31:43      阅读:2811      评论:0      收藏:0      [点我收藏+]

标签:第一个   col   网址   hello   gpo   nbsp   class   color   bs4   

select find和find_all有什么区别呢,请看代码:

from bs4 import BeautifulSoup

html =‘‘‘<head>hello python</head>
<body>
    <div class=‘ming‘>
        <div class=‘lily‘ id=‘ben‘>赵丽丽是个大笨蛋</div>
        <div class=‘lily‘ id=‘ben‘>赵丽丽是个大笨蛋吗?</div>
        <a href = ‘www.mingmig.com‘>我的网址</a>
        <a href = ‘www.mingmig.com‘>我的网址</a>
    </div>
    
</body>
‘‘‘ 
soup = BeautifulSoup(html, lxml)
s = soup.select(div .lily)#select的写法和find有区别,select是标签和class都在一个字符串里,find是两个字符串,用逗号隔开
f = soup.find(div,class_ = lily) #find只取第一个值,返回的是字符串
fa = soup.find_all(div,class_ = lily)#find——all是全部的值和select一样,是一个列表
fal = soup.find_all(div,class_ = lily,limit=1)#find——all是全部的值和select一样,是一个列表,加limit属性后只返回第一个
print(s)
print(f)
print(fa)
print(fal)

>>>

[<div class="lily" id="ben">赵丽丽是个大笨蛋</div>, <div class="lily" id="ben">赵丽丽是个大笨蛋吗?</div>]
<div class="lily" id="ben">赵丽丽是个大笨蛋</div>
[<div class="lily" id="ben">赵丽丽是个大笨蛋</div>, <div class="lily" id="ben">赵丽丽是个大笨蛋吗?</div>]
[<div class="lily" id="ben">赵丽丽是个大笨蛋</div>]

 

BeautifulSoup之select find和find_all

标签:第一个   col   网址   hello   gpo   nbsp   class   color   bs4   

原文地址:https://www.cnblogs.com/Zhu-Xueming/p/8414538.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!