【问题标题】:Extending selection with BeautifulSoup使用 BeautifulSoup 扩展选择
【发布时间】:2012-03-18 08:42:50
【问题描述】:

我正在尝试让 BeautifulSoup 执行以下操作。

我有想要修改的 HTML 文件。我对两个标签特别感兴趣,我称之为 TagA 的标签是

<div class ="A">...</div>

还有一个我称之为 TagB

<p class = "B">...</p>

这两个标签在整个 HTML 中独立出现,它们本身可能包含其他标签并嵌套在其他标签中。 我想在每个 TagA 周围放置一个标记标记,只要 TagB 没有立即跟随,这样

<p class="A"">...</p> becomes <marker><p class="A">...</p></marker>

但是当 TagA 紧跟在 TagB 之后时,我希望标记 Tag 将它们都包围起来

这样

<p class="A">...</p><div class="B">...</div> 
becomes 
<marker><p class="A">...</p><div class="B">...</div></marker>

我可以看到如何选择 TagA 并用标记标记将其括起来,但是当它后面跟着 TagB 时,我不知道 BeautiulSoup 的“选择”是否或如何扩展以包含 NextSibling。 任何帮助表示赞赏。

【问题讨论】:

    标签: python html beautifulsoup


    【解决方案1】:

    beautifulSoup 确实具有“下一个兄弟”功能。找到A类的所有标签,用a.next_sibling判断是不是b。

    查看文档:

    http://www.crummy.com/software/BeautifulSoup/bs4/doc/#going-sideways

    【讨论】:

    • 谢谢 - 但是如何将两个标签一起选择以便将它们都放在我的标记标签中?
    【解决方案2】:

    我认为我试图将“选择”从一个标签扩展到以下标签是错误的。相反,我发现下面的代码插入了外部“标记”标签,然后插入了 A 和 B 标签就可以了。 我对 Python 还是很陌生,因此希望能就以下改进或障碍提供建议。

    def isTagB(tag):
    #If tag is <p class = "B"> return true
    #if not - or tag is just a string return false
        try:
            return tag.name == 'p'#has_key('p') and tag.has_key('B')
        except:
            return False
    
    from bs4 import BeautifulSoup
    
    soup = BeautifulSoup("""<div class = "A"><p><i>more content</i></p></div><div class = "A"><p><i>hello content</i></p></div><p class="B">da <i>de</i> da </p><div class = "fred">not content</div>""")
    
    
    for TagA in soup.find_all("div", "A"):
        Marker = soup.new_tag('Marker')
        nexttag = TagA.next_sibling
        #skipover white space
        while str(nexttag).isspace():
            nexttag = nexttag.next_sibling
        if isTagB(nexttag):
            TagA.replaceWith(Marker)   #Put it where the A element is
            Marker.insert(1,TagA)
            Marker.insert(2,nexttag)
        else:
            #print("FALSE",nexttag)
            TagA.replaceWith(Marker)   #Put it where the A element is
            Marker.insert(1,TagA)
    print (soup)
    

    【讨论】:

      【解决方案3】:
      import urllib
      from BeautifulSoup import BeautifulSoup
      html = urllib.urlopen("http://ursite.com") #gives html response
      soup = BeautifulSoup(html)
      
      all_div = soup.findAll("div",attrs={}) #use attrs as dict for attribute parsing 
      #exa- attrs={'class':"class","id":"1234"}
      
      single_div = all_div[0]
      
      #to find p tag inside single_div
      p_tag_obj = single_div.find("p")
      

      你可以使用 obj.findNext(), obj.findAllNext(), obj.findALLPrevious(), obj.findPrevious(), 要获取属性,您可以使用 obj.get("href")、obj.get("title") 等。

      【讨论】:

        猜你喜欢
        • 2016-03-27
        • 2013-06-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-05-22
        • 1970-01-01
        相关资源
        最近更新 更多