문제

from BeautifulSoup import BeautifulStoneSoup

xml_data = """
<doc>
  <test>test</test>
  <foo:bar>Hello world!</foo:bar>
</doc>
"""

soup = BeautifulStoneSoup(xml_data)
print soup.prettify()
make = soup.find('foo:bar')
print make
# prints <foo:bar>Hello world!</foo:bar>

make.contents = ['Top of the world Ma!']
print make
# prints <foo:bar></foo:bar>

컨텐츠를 잃지 않고 요소의 내용,이 경우 변수 "make"의 요소를 어떻게 변경합니까? 기존의 XML 문서를 수정할 수있는 다른 순수한 파이썬 모듈을 가리킬 수 있다면 알려주십시오.

추신! BeautifulSoup은 HTML과 XML의 스크린 획득 및 구문 분석에 적합합니다!

도움이 되었습니까?

해결책

확인하십시오 문서화 replaceWith. 이것은 작동합니다 :

make.contents[0].replaceWith('Top of the world Ma!')

다른 팁

BeautifulSoup 버전 4 (bs4), 당신은 동일하게 달성 할 수 있습니다 업데이트 string 재산 곧장 :

from bs4 import BeautifulSoup

xml_data = """
<doc>
  <test>test</test>
  <foo:bar>Hello world!</foo:bar>
  <parent>Hello <child>world!</child></parent>
</doc>
"""

soup = BeautifulSoup(xml_data)
make = soup.find('foo:bar')

make.string = 'Top of the world Ma!'
print make
# prints <foo:bar>Top of the world Ma!</foo:bar>

이 접근법은 요소에 다른 요소가 포함되어있는 경우에 적합하며 전체 컨텐츠를 새로운 컨텐츠로 교체하려고합니다.

parent = soup.find('parent')
parent.string = 'Top of the world Ma!'

print parent
# prints <parent>Top of the world Ma!</parent>

나는 지금이 오래된 질문에 부딪쳤다. 그리고 제공된 해결책은 나에게 적합하지 않았다. 추가 연구는 위의 접근 방식으로 이어지고, 여기서 사용한 것을 공유하는 것이 유용하다고 생각했습니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top