2012-03-18 89 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(”标题“)等