2012-03-18 73 views
1

我正在嘗試使BeautifulSoup執行以下操作。使用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> 

但當塔加由TAGB立即其次,我希望標記標籤包圍他們倆

使

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

我可以看到如何選擇塔加與標識器標籤封裝,但是當它後跟TagB我不知道是否或如何擴展BeautiulSoup的'選擇'以包含NextSibling。 任何幫助表示讚賞。

回答

0

我認爲,試圖從一個標籤下面延長「選擇」我要對這個錯誤的方式。相反,我發現下面的代碼將外部'Marker'標籤插入,然後插入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) 
0
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(」標題「)等