返回BeautifulGroup中不确定数量的段落

2024-09-26 22:50:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我刚开始使用BeautifulSoup,我试图制作一个脚本,它将转到一些非常相似的页面,然后返回一个部分下面的所有段落。目前我有以下代码

def BrightstormPageTest():
    soup = Soup(urllib.urlopen('http://brightstorm.com/science/chemistry/chemical-reaction-rates/collision-theory/').read())
    relevantTagText = ""
    for element in soup.findAll("section"):
            print element.nextSibling

这对第一段来说很好,但是有两个部分是我想要的兄弟姐妹的,第一部分总是只有一个段落,而第二部分可能有1到10之间的未定数字。有什么办法吗?在

相关html:

^{pr2}$

我只想了解这些段落的内容。在


Tags: 代码脚本comhttpdef页面elementurllib
1条回答
网友
1楼 · 发布于 2024-09-26 22:50:01

您需要迭代部分,然后迭代段落。为了演示,我修改了您的代码以打印每个段落的文本。在

from bs4 import BeautifulSoup as Soup

def BrightstormPageTest():
    soup = Soup(urllib.urlopen('http://brightstorm.com/science/chemistry/chemical-reaction-rates/collision-theory/').read())
    sections = soup.findAll("section")
    for section in sections:
        ps = section.findAll("p")
        for p in ps:
            print p.text

def BrightstormPageTest2():
    soup = Soup(urllib.urlopen('http://brightstorm.com/science/chemistry/chemical-reaction-rates/collision-theory/').read())
    sections = soup.findAll("section")
    for section in sections:
        while True:
             try:
                 print section.nextSibling.text
             except TypeError:
                 # .text is a valid method on a <p> element, but not a NavigableString.  
                 break

相关问题 更多 >

    热门问题