2015-11-04 291 views
0

我想我缺少一些基本的東西。我想訪問XML元素的文本並將其替換。舉例來說,如果我有這樣的:
<name>Fred</name>我希望能夠改變FredJohn在Python中替換XML元素的文本內容

我已經讀了很多關於ElementTree的和BeautifulSoup網站,但我仍然堅持。有人能提供一個非常簡單的例子嗎?

回答

1

是這樣的?

  1. 使用BeautifulSoup的soup.find()方法來查找HTML標籤:

    >>> from bs4 import BeautifulSoup 
    >>> BeautifulSoup('<html><body><name>Fred</name><html><body>') 
    >>> soup = BeautifulSoup('<html><body><name>Fred</name><html><body>') 
    >>> name = soup.find('name') 
    >>> name 
    <name>Fred</name> 
    >>> 
    
  2. 使用tag.string = newstring來取代它的字符串:

    >>> name.string = 'John' 
    >>> name 
    <name>John</name> 
    >>> soup 
    <html><body><name>John</name><html><body></body></html></body></html> 
    >>> 
    

然後我們做了,檢查the document更多細節。

0

爲什麼不把它解析爲文本?數據的格式並不總是需要使用特殊的庫來處理它。

>>> a = 'stuff<name>Fred</name>otherstuff' 
>>> a.replace('<name>Fred</name>', '<name>John</name>') 
'stuff<name>John</name>otherstuff' 
1

使用A python2.7版本的美麗湯

from BeautifulSoup import BeautifulSoup 
soup=BeautifulSoup("<name>Fred</name>") 
soup.find("name").string="John" 
print(soup) 

輸出

<name>John</name> 

替代正則表達式

import re 
htmltext="<name>John</name>" 
new_htmltext=re.sub("(<name>).*(</name>)","\\1Fred\\2",htmltext) 
print(new_htmltext)