【问题标题】:How to find all <li>'s within a specific <ul> class?如何在特定的 <ul> 类中找到所有 <li>?
【发布时间】:2013-06-19 06:38:39
【问题描述】:

环境:

靓汤4

Python 2.7.5

逻辑:

“find_all”&lt;li&gt; 实例在 &lt;ul&gt; 中,类为 my_class,例如:

<ul class='my_class'>
<li>thing one</li>
<li>thing two</li>
</ul>

澄清:只需获取&lt;li&gt; 标签之间的“文本”。

Python 代码:

(下面的find_all不正确,我只是把它放在上下文中)

from bs4 import BeautifulSoup, Comment
import re

# open original file
fo = open('file.php', 'r')
# convert to string
fo_string = fo.read()
# close original file
fo.close()
# create beautiful soup object from fo_string
bs_fo_string = BeautifulSoup(fo_string, "lxml")
# get rid of html comments
my_comments = bs_fo_string.findAll(text=lambda text:isinstance(text, Comment))
[my_comment.extract() for my_comment in my_comments]

my_li_list = bs_fo_string.find_all('ul', 'my_class')

print my_li_list

【问题讨论】:

    标签: python python-2.7 beautifulsoup


    【解决方案1】:

    这个?

    >>> html = """<ul class='my_class'>
    ... <li>thing one</li>
    ... <li>thing two</li>
    ... </ul>"""
    >>> from bs4 import BeautifulSoup as BS
    >>> soup = BS(html)
    >>> for ultag in soup.find_all('ul', {'class': 'my_class'}):
    ...     for litag in ultag.find_all('li'):
    ...             print litag.text
    ... 
    thing one
    thing two
    

    解释:

    soup.find_all('ul', {'class': 'my_class'}) 查找类为my_class 的所有ul 标记。

    然后我们在那些ul标签中找到所有li标签,并打印标签的内容。

    【讨论】:

    • 谢谢,我理解这个逻辑,当我将fo_string 更改为带有bs_fo_string = BeautifulSoup(fo_string, "lxml") 的漂亮汤对象并打印bs_fo_string 时,我可以看到&gt; 已变为@987654331 @ 和 &amp;lt; 已更改为 &amp;lt;。所以使用find_all 会显示一个空列表,因为它找不到ulli。有谁知道为什么会发生这种向字符实体的转换以及如何阻止它?
    • @user1063287 fo_string 看起来像什么?编辑您的问题以将其添加到
    • 我糟糕的、格式错误的 html、fo_string 中的类名在关闭 " 时丢失了!代码现在正在工作。谢谢。
    【解决方案2】:

    BeautifulSoup3 可以解决这个问题,这台机器上没有 4 个。

    >>> [li.string for li in bs_fo_string.find('ul', {'class': 'my_class'}).findAll('li')]
    [u'thing one', u'thing two']
    

    这个想法是首先搜索具有'my_class'类的ul,然后查找该ul中的所有li。

    如果您有其他具有相同类的 ul,您可能还想在 ul 搜索中使用 findAll,并将列表推导更改为嵌套。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-29
      • 2013-11-17
      • 1970-01-01
      • 1970-01-01
      • 2015-12-06
      • 2012-12-13
      相关资源
      最近更新 更多