1

Python と BS4 でコードを書くのに問題があります。

次の段落があると仮定します。

<p id="paragraph">
Here is the paragraph <a href="/" id="url">Here an url</a> the paragraph continues.
</p>

ID を取得しreplace_with、文字列を置き換えるために使用します (P および A タグ内)。しかし、この場合、結果は次のようになります。

Here is the paragraph the paragraph continues. Here an url

構造は尊重されません。正しい方法は何ですか?

コードを追加します。

page = open('file.html')
soupPage = BeautifulSoup(page)
findId = soupPage.find(id='nameOfId')
findId.replace_with('NewString')
4

1 に答える 1

2

これを試して:

from bs4 import BeautifulSoup

page = open('file.html')
soupPage = BeautifulSoup(page)
findId = soupPage.find(id='url')
findId.contents[0].replace_with('NewString')
print soupPage

プリント:

<html><body><p id="paragraph">
Here is the paragraph <a href="/" id="url">NewString</a> the paragraph continues.
</p></body></html>

それがあなたが望んでいたものであることを願っています。

于 2013-05-29T20:50:28.823 に答える