Beautiful Soup是一個可以從HTML或XML檔案中擷取資料的Python 函式庫。它能夠透過你喜歡的轉換器實現慣用的文檔導航、尋找、修改文件的方式。他也能夠修改HTML/XML文件的內容。這篇文章主要介紹了Python利用Beautiful Soup模組來修改內容的方法,需要的朋友可以參考下。
前言
其實Beautiful Soup 模組除了能夠搜尋和導航之外,還能夠修改 HTML/XML 文件的內容。這就意味著能夠新增或刪除標籤、修改標籤名稱、改變標籤屬性值和修改文字內容等等。這篇文章非常詳細的跟大家介紹了Python利用Beautiful Soup模組修改內容的方法,下面話不多說,來看看詳細的介紹吧。
修改標籤
使用的範例HTML 文件還是如下:
html_markup=""" <p> </p>
-
plants
100000
-
algae
100000
修改標籤名稱
soup = BeautifulSoup(html_markup,'lxml') producer_entries = soup.ul print producer_entries.name producer_entries.name = "p" print producer_entries.prettify()
修改標籤屬性值
# 修改标签属性 # 更新标签现有的属性值 producer_entries['id'] = "producers_new_value" print producer_entries.prettify() # 标签添加新的属性值 producer_entries['class'] = "newclass" print producer_entries.prettify() # 删除标签属性值 del producer_entries['class'] print producer_entries.prettify()
新增新的標籤
我們可以使用new_tag 方法來產生一個新的標籤,然後使用append()
、insert()
、insert_after()
、insert_before()
方法來將標籤新增至HTML樹中。
例如在上述的 HTML 文件的 ul 標籤中新增一個 li 標籤 。首先要產生新的 li 標籤,然後將其插入到 HTML 樹結構中 。並在 li 標籤中插入對應的 p 標籤。
# 添加新的标签 # new_tag 生成一个 tag 对象 new_li_tag = soup.new_tag("li") # 标签对象添加属性的方法 new_atag = soup.new_tag("a",href="www.example.com" rel="external nofollow" ) new_li_tag.attrs = {'class':'producerlist'} soup = BeautifulSoup(html_markup,'lxml') producer_entries = soup.ul # 使用 append() 方法添加到末尾 producer_entries.append(new_li_tag) print producer_entries.prettify() # 生成两个 p 标签,将其插入到 li 标签中 new_p_name_tag = soup.new_tag("p") new_p_name_tag['class'] = "name" new_p_number_tag = soup.new_tag("p") new_p_number_tag["class"] = "number" # 使用 insert() 方法指定位置插入 new_li_tag.insert(0,new_p_name_tag) new_li_tag.insert(1,new_p_number_tag) print new_li_tag.prettify()
修改字串內容
修改字串內容可以使用new_string()
、append( )
、insert()
方法。
# 修改字符串内容 # 使用 .string 属性修改字符串内容 new_p_name_tag.string = 'new_p_name' # 使用 .append() 方法添加字符串内容 new_p_name_tag.append("producer") # 使用 soup 对象的 new_string() 方法生成字符串 new_string_toappend = soup.new_string("producer") new_p_name_tag.append(new_string_toappend) # 使用insert() 方法插入 new_string_toinsert = soup.new_string("10000") new_p_number_tag.insert(0,new_string_toinsert) print producer_entries.prettify()
刪除標籤節點
Beautiful Soup 模組提供了decompose()
和extract()
方法來刪除節點。
decompose()
方法刪除節點,不僅會刪除目前節點,還會刪除其子節點一塊了。
extract()
方法用來從 HTML 樹中刪除節點或字串內容。
# 删除节点 third_producer = soup.find_all("li")[2] # 使用 decompose() 方法删除 p 节点 p_name = third_producer.p p_name.decompose() print third_producer.prettify() # 使用 extract() 方法删除节点 third_producer_removed = third_producer.extract() print soup.prettify()
刪除標籤內容
標籤可能有NavigableString 物件或Tag 物件作為它的子節點,移除所有的這些子節點可以使用clear( )
方法。這將會移除標籤的所有的 .content。
修改內容的其他方法
除了上面說到的方法,還有其他方法用來修改內容。
insert_after()
和insert_before()
方法
上面的兩個方法能夠在標籤或字串的前面或後面插入一個標籤或者字串。方法只能接收一個參數,要嘛是 NavigableString 物件要嘛是 Tag 物件。
replace_with()
方法
該方法是用一個新的標籤或字串內容取代原來的標籤或字串,能夠接收一個標籤或字串作為輸入。
wrap()
和unwrap()
方法
wrap()
方法是用另一個標籤來包一個標籤或者字串。
unwrap()
方法則和 wrap()
方法相反。
# wrap()方法 li_tags = soup.find_all('li') for li in li_tags: new_p_tag = soup.new_tag('p') li.wrap(new_p_tag) print soup.prettify() # unwrap()方法 li_tags = soup.find_all("li") for li in li_tags: li.p.unwrap() print soup.prettify()
以上是詳解Python利用Beautiful Soup模組修改內容範例程式碼的詳細內容。更多資訊請關注PHP中文網其他相關文章!

Tomergelistsinpython,YouCanusethe操作員,estextMethod,ListComprehension,Oritertools

在Python3中,可以通過多種方法連接兩個列表:1)使用 運算符,適用於小列表,但對大列表效率低;2)使用extend方法,適用於大列表,內存效率高,但會修改原列表;3)使用*運算符,適用於合併多個列表,不修改原列表;4)使用itertools.chain,適用於大數據集,內存效率高。

使用join()方法是Python中從列表連接字符串最有效的方法。 1)使用join()方法高效且易讀。 2)循環使用 運算符對大列表效率低。 3)列表推導式與join()結合適用於需要轉換的場景。 4)reduce()方法適用於其他類型歸約,但對字符串連接效率低。完整句子結束。

pythonexecutionistheprocessoftransformingpypythoncodeintoExecutablestructions.1)InternterPreterReadSthecode,ConvertingTingitIntObyTecode,whepythonvirtualmachine(pvm)theglobalinterpreterpreterpreterpreterlock(gil)the thepythonvirtualmachine(pvm)

Python的關鍵特性包括:1.語法簡潔易懂,適合初學者;2.動態類型系統,提高開發速度;3.豐富的標準庫,支持多種任務;4.強大的社區和生態系統,提供廣泛支持;5.解釋性,適合腳本和快速原型開發;6.多範式支持,適用於各種編程風格。

Python是解釋型語言,但也包含編譯過程。 1)Python代碼先編譯成字節碼。 2)字節碼由Python虛擬機解釋執行。 3)這種混合機制使Python既靈活又高效,但執行速度不如完全編譯型語言。

UseeAforloopWheniteratingOveraseQuenceOrforAspecificnumberoftimes; useAwhiLeLoopWhenconTinuingUntilAcIntiment.forloopsareIdealForkNownsences,而WhileLeleLeleLeleLeleLoopSituationSituationsItuationsItuationSuationSituationswithUndEtermentersitations。

pythonloopscanleadtoerrorslikeinfiniteloops,modifyingListsDuringteritation,逐個偏置,零indexingissues,andnestedloopineflinefficiencies


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

SublimeText3 Linux新版
SublimeText3 Linux最新版

SublimeText3漢化版
中文版,非常好用

Dreamweaver CS6
視覺化網頁開發工具

VSCode Windows 64位元 下載
微軟推出的免費、功能強大的一款IDE編輯器

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)