Python에서 BeautifulSoup을 사용하고 일부 태그를 바꾸는 데 문제가 있습니다. 나는 <div>
태그를 찾고 아이들을 확인하고 있습니다. 그 아이들이 아이들을 가지고 있지 않다면 (NODE_TYPE = 3의 텍스트 노드입니다), 나는 이것을 <p>
으로 복사하고 있습니다. 나도 같은 for 루프에서 node
에 최대 높은 대체 할replaceWith를 사용하여 Python에서 BeautifulSoup로 HTML 태그를 바꾸는 데 문제가 발생했습니다.
File "file.py", line 125, in function
node.replaceWith(newTag)
File "BeautifulSoup.py", line 131, in replaceWith
myIndex = self.parent.index(self)
AttributeError: 'NoneType' object has no attribute 'index'
하고 올바르게 작동합니다
from BeautifulSoup import Tag, BeautifulSoup
class bar:
self.soup = BeautifulSoup(self.input)
foo()
def foo(self):
elements = soup.findAll(True)
for node in elements:
# ....other stuff here if not <div> tags.
if node.name.lower() == "div":
if not node.find('a'):
newTag = Tag(self.soup, "p")
newTag.setString(node.text)
node.replaceWith(newTag)
nodesToScore.append(newTag)
else:
for n in node.findAll(True):
if n.getString(): # False if has children
newTag = Tag(self.soup, "p")
newTag.setString(n.text)
n.replaceWith(newTag)
가 나는 AttributeError를 얻고있다. 노드를 통해 반복되는 n 때문에 문제가 있다고 가정합니다.
내가 잘못했거나 더 좋은 방법은 무엇일까요? 감사! PS. 내가 구글 AppEngine에와 BeautifulSoup로 3.0.8.1 파이썬 2.5을 사용하고
'node.replaceWith'와'n.replaceWith'를 확인해 주셔서 감사합니다. 내가 추가 된 코드를 추가했습니다. 'else'가 없다면'not if'가 정상적으로 실행되기 때문에 관련성이 없다고 생각하는 이유가 있지만 잘못되었습니다. – feesta
@feesta : HTML을 보지 않고도 디버그하기가 어렵습니다. 문제에 해당하는 HTML을 어떻게 찾을 수 있는지 제안하는 편집 (위)을 추가했습니다. – unutbu
@ ~ 우분투 감사합니다! 지금 일하고있어! 만약 node.parent가 None이면 (log node) else : (나머지는)'잘못된 HTML은 공백 만있는'div' 태그였습니다. 그게 내가 벗기는 부분의 일부 야. 다시 한번 감사드립니다! – feesta