2012-03-18 5 views
1

다음을 수행하기 위해 BeautifulSoup을 얻으려고합니다.BeautifulSoup로 선택 확장

수정하고 싶은 HTML 파일이 있습니다. 나는 특히이 개 태그, 내가 타가을 호출 한 관심이 두 태그는 HTML에 걸쳐 독립적으로 발생 내가 TagB

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

를 호출합니다

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

과 하나되는 오전 자체가 다른 태그를 포함 할 수있다 다른 태그 안에 중첩 될 수 있습니다. 이 즉시 타가 가 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 'selection'이 NextSibling을 포함하도록 확장 될 수 있는지 또는 어떻게 될지 모르겠습니다. 도움을 주시면 감사하겠습니다.

답변

0

난 다음에 하나 개의 태그에서 '선택'을 확장하는 시도하여 이것에 대해 잘못된 길을 가고 있었다 생각합니다. 대신 바깥 쪽 'Marker'태그를 삽입 한 다음 A 및 B 태그를 삽입하여 트릭을 수행하는 다음 코드를 발견했습니다. 저는 파이썬에 대해 아주 익숙해 졌으므로 다음과 같은 개선점이나 문제에 관해 조언 해 주시면 감사하겠습니다.

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.get 사용할 수있는 속성을 얻을 수 obj.findNext(), obj.findAllNext(), obj.findALLPrevious(), obj.findPrevious(), 을 사용할 수 있습니다 "HREF "), obj.get ("title ") 등