【问题标题】:How to determine a logic part with python's beautiful soup when crawling爬取时如何用python beautifulsoup判断逻辑部分
【发布时间】:2015-09-17 04:40:11
【问题描述】:

所以现在我总是有架构:

<h2 class="dot">headline 1</h2>
<p>text</p>
<h2 class="dot">headline 2</h2>
<p>text</p>

但我抓取的某些网站可能具有以下架构:

<h2 class="dot">headline 1</h2>
<p>text</p>
<p>text</p>
<h2 class="dot">headline 2</h2>
<p>text</p>

我是这样爬的:

for product in soup.findAll("p"):

我没有办法确定不同的 p 元素是否属于一起。有人知道我如何确定一个或两个 p 属于同一个逻辑单元吗?

一种可能的方法是确定前一个 html 元素是 p 还是 h2。有什么好办法查出来吗?

【问题讨论】:

  • 所有元素都属于同一个父元素吗?我假设您要说的是要将其拆分为每个

    元素正下方的所有

    元素的组。

  • 是的,这将是一个解决方案。我该怎么做?

标签: python beautifulsoup web-crawler


【解决方案1】:

给你:

from bs4 import BeautifulSoup

html="""
<div>
<h2 class="dot">headline 1</h2>
<p>text</p>
<p>text</p>
<h2 class="dot">headline 2</h2>
<p>text</p>
</div>
"""

soup = BeautifulSoup(html)

for h2 in soup.findAll("h2"):
    group = []
    node = h2.next_sibling

    while node is not None and node.name != "h2":
        group.append(node)
        node = node.next_sibling

    # Do w/e you want w/ the group
    print group

我所做的是遍历所有 h2 元素,遍历它们的下一个兄弟元素并将它们附加到一个列表中,直到你用完兄弟元素或遇到另一个 h2。如果你只想要 &lt;p&gt; 元素,那么你应该改变:

group.append(node)

到:

if node.name == "p":
    group.append(node)

哦,作为最后的评论。除非您确实需要一个列表,否则最好只使用循环内的内容而不是将其添加到列表中,如下所示:

from bs4 import BeautifulSoup

html="""
<div>
<h2 class="dot">headline 1</h2>
<p>text</p>
<p>text</p>
<h2 class="dot">headline 2</h2>
<p>text</p>
</div>
"""

soup = BeautifulSoup(html)

for h2 in soup.findAll("h2"):
    node = h2.next_sibling

    print "This h2", h2

    while node is not None and node.name != "h2":
        if node.name == "p":
            print node
        node = node.next_sibling

输出:

This h2 <h2 class="dot">headline 1</h2>
<p>text</p>
<p>text</p>
This h2 <h2 class="dot">headline 2</h2>
<p>text</p>

【讨论】:

  • 您好,感谢您的回复,但它不起作用。它将 p 个元素放在不同的组中
  • 刚刚添加了一些输出以进行澄清。你是说你没有得到我得到的,或者那不是你想要的?
  • 嘿,随着“if node.name == "p": group.append(node)"" 的变化,它正在工作。非常大 THX!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-10-24
  • 1970-01-01
  • 1970-01-01
  • 2015-03-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多