【问题标题】:BeautifulSoup: pulling a tag preceding another tagBeautifulSoup:在另一个标签之前拉一个标签
【发布时间】:2016-06-21 13:06:18
【问题描述】:

我正在拉取网页上的列表并为它们提供上下文,我还拉取紧接在它们之前的文本。拉出<ul><ol> 之前的标签似乎是最好的方法。所以假设我有这个列表:

我想拔出子弹和“千禧一代”这个词。我使用 BeautifulSoup 函数:

#pull <ul> tags
def pull_ul(tag):
    return tag.name == 'ul' and tag.li and not tag.attrs and not tag.li.attrs and not tag.a 
ul_tags = webpage.find_all(pull_ul)
#find text immediately preceding any <ul> tag and append to <ul> tag 
ul_with_context = [str(ul.previous_sibling) + str(ul) for ul in ul_tags]

当我打印 ul_with_context 时,我得到以下信息:

['\n<ul>\n<li>With immigration adding more numbers to its group than any other, the Millennial population is projected to peak in 2036 at 81.1 million. Thereafter the oldest Millennial will be at least 56 years of age and mortality is projected to outweigh net immigration. By 2050 there will be a projected 79.2 million Millennials.</li>\n</ul>']

如您所见,“千禧一代”并未被取消。我从中提取的页面是http://www.pewresearch.org/fact-tank/2016/04/25/millennials-overtake-baby-boomers/ 这是子弹的代码部分:

&lt;p&gt;&lt;ul&gt; 标签是同级的。知道为什么它没有拉出带有 “千禧一代” 字样的标签吗?

【问题讨论】:

    标签: python-2.7 beautifulsoup


    【解决方案1】:

    Previous_sibling 将返回标签之前的元素字符串。在您的情况下,它返回字符串'\n'

    相反,您可以使用findPrevious method 来获取所选内容之前的节点:

    doc = """
    <h2>test</h2>
    <ul>
        <li>1</li>
        <li>2</li>
    </ul>
    """
    
    soup = BeautifulSoup(doc, 'html.parser')    
    tags = soup.find_all('ul')
    
    
    print [ul.findPrevious() for ul in tags]
    print tags
    

    将输出:

    [<h2>test</h2>]
    [<ul><li>1</li><li>2</li></ul>]
    

    【讨论】:

    • 在我使用的BeautifulSoup的当前版本中,方法是find_previous()而不是findPrevious()
    • 请注意,find_previous() 将返回前一个元素。不管水平与否。而find_previous_sibling() 将返回位于同一级别(兄弟)的前一个元素。了解差异并自行判断您需要什么。
    猜你喜欢
    • 1970-01-01
    • 2015-06-24
    • 2019-11-30
    • 2023-01-04
    • 1970-01-01
    • 1970-01-01
    • 2013-04-17
    • 2021-05-02
    • 1970-01-01
    相关资源
    最近更新 更多