2017-10-30 6 views
1

Beautifulsoup을 사용하여 얻은 HTML 태그의 inner text을 변경하고 싶습니다. 나는 그것이 ID에 의해 년대 태그를 얻기 위해 관리해야beautifulsoup python을 사용하여 내부 태그의 텍스트를 변경하십시오.

<a href="index.html" id="websiteName">Bar</a> 

:

HTMLDocument.find(id='websiteName') 

하지만 할 수 beeing는 아니에요

예 :에

<a href="index.html" id="websiteName">Foo</a> 

가집니다 태그의 inner text을 다음과 같이 변경하십시오.

print HTMLDocument.find(id='websiteName') 

a = HTMLDocument.find(id='websiteName') 
a = a.replaceWith('<a href="index.html" id="websiteName">Bar</a>') 

// I have tried using this as well 
a = a.replaceWith('Bar') 

print a 

출력 : 문자열 요소를 변경하여

<a href="index.html" id="websiteName">Foo</a> 
<a href="index.html" id="websiteName">Foo</a> 
+0

이를 반영합니다. 이제'a = a.replace ('Bar')'를 실행하고 나서'a' 변수를 직접 출력합니다 –

+0

어떤 버전의 Beautifulsoup를 사용하고 있습니까? – PRMoureu

+0

'.replaceWith()'메소드는 아무것도 리턴합니까? – AK47

답변

1

시도 : 나는 질문을 편집 한

HTMLDocument.find(id='websiteName').string.replace_with('Bar') 

from bs4 import BeautifulSoup as soup 

html = """ 
<a href="index.html" id="websiteName">Foo</a> 
""" 
soup = soup(html, 'lxml') 
result = soup.find(id='websiteName') 

print(result) 
# >>> <a href="index.html" id="websiteName">Foo</a> 

result.string.replace_with('Bar') 
print(result) 
# >>> <a href="index.html" id="websiteName">Bar</a> 
+0

정확히 무엇을할까요? –

+1

'replace_with()'메소드가'3.2.1' 내 버전에서 작동하는 것은 가치가 없다. –

+0

주목 해 주셔서 고맙습니다.이 버전을 테스트 할 수 없습니다. – PRMoureu

관련 문제