BeautifulSoup - 帮我挑选 div 和类
这是我的 HMTL 代码:
<div class="BlockA">
<h4>BlockA</h4>
<div class="name">John Smith</div>
<div class="number">2</div>
<div class="name">Paul Peterson</div>
<div class="number">14</div>
</div>
<div class="BlockB">
<h4>BlockB</h4>
<div class="name">Steve Jones</div>
<div class="number">5</div>
</div>
注意 BlockA
和 BlockB
。两者都包含相同的元素,即 name
和 number
,但位于不同的类中。我是 python 新手,正在考虑尝试类似的方法:
parsedHTML = soup.findAll("div", attrs={"name" : "number"})
但这只会给我一个空白屏幕。我是否可以从 blockA
中执行 findAll
,显示数据,然后从 BlockB
启动另一个循环并执行相同操作?
谢谢。
编辑:对于那些询问的人,我想简单地循环遍历 JSON 中的值和输出,如下所示:
BlockA
John Smith
2
Paul Peterson
14
BlockB
Steve Whoever
123
Mr Whathisface
23
Heres my HMTL code:
<div class="BlockA">
<h4>BlockA</h4>
<div class="name">John Smith</div>
<div class="number">2</div>
<div class="name">Paul Peterson</div>
<div class="number">14</div>
</div>
<div class="BlockB">
<h4>BlockB</h4>
<div class="name">Steve Jones</div>
<div class="number">5</div>
</div>
Notice BlockA
and BlockB
. Both contain the same elements, ie name
and number
but are inside seperate classes. I'm new to python and was thinking of trying something like:
parsedHTML = soup.findAll("div", attrs={"name" : "number"})
but that just gives me a blank screen. Is it possible for me to do a findAll
from within blockA
, display the data, then start another loop from BlockB
and do the same?
Thanks.
EDIT: For those asking, I want to simply loop through the values and output in JSON like this:
BlockA
John Smith
2
Paul Peterson
14
BlockB
Steve Whoever
123
Mr Whathisface
23
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您想查找包含“名称”或“数字”类属性的 div 吗?
You want to find divs that contain a class attribute of "name" or "number"?
您需要使用可能的
class
值的列表。看到您的编辑后:
原始 HTML 片段的输出将是:
You need to use a list of possible
class
values.After seeing your edit:
And the output for your original HTML snippet would be: