国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python利用Beautiful Soup模塊修改內(nèi)容方法示例

2020-02-23 04:29:37
字體:
供稿:網(wǎng)友

前言

其實Beautiful Soup 模塊除了能夠搜索和導(dǎo)航之外,還能夠修改 HTML/XML 文檔的內(nèi)容。這就意味著能夠添加或刪除標簽、修改標簽名稱、改變標簽屬性值和修改文本內(nèi)容等等。這篇文章非常詳細的給大家介紹了Python利用Beautiful Soup模塊修改內(nèi)容的方法,下面話不多說,來看看詳細的介紹吧。

修改標簽

使用的示例 HTML 文檔還是如下:

html_markup=""" <div class="ecopyramid"> <ul id="producers">  <li class="producerlist">  <div class="name">plants</div>  <div class="number">100000</div>  </li>  <li class="producerlist">  <div class="name">algae</div>  <div class="number">100000</div>  </li> </ul> </div> """

修改標簽名稱

soup = BeautifulSoup(html_markup,'lxml')producer_entries = soup.ulprint producer_entries.nameproducer_entries.name = "div"print producer_entries.prettify()

修改標簽屬性值

# 修改標簽屬性# 更新標簽現(xiàn)有的屬性值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 樹結(jié)構(gòu)中 。并在 li 標簽中插入相應(yīng)的 div 標簽。

# 添加新的標簽# 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()# 生成兩個 div 標簽,將其插入到 li 標簽中new_div_name_tag = soup.new_tag("div")new_div_name_tag['class'] = "name"new_div_number_tag = soup.new_tag("div")new_div_number_tag["class"] = "number"# 使用 insert() 方法指定位置插入new_li_tag.insert(0,new_div_name_tag)new_li_tag.insert(1,new_div_number_tag)print new_li_tag.prettify()

修改字符串內(nèi)容

修改字符串內(nèi)容可以使用 new_string()  、append()insert() 方法。

# 修改字符串內(nèi)容# 使用 .string 屬性修改字符串內(nèi)容new_div_name_tag.string = 'new_div_name'# 使用 .append() 方法添加字符串內(nèi)容new_div_name_tag.append("producer")# 使用 soup 對象的 new_string() 方法生成字符串new_string_toappend = soup.new_string("producer")new_div_name_tag.append(new_string_toappend)# 使用insert() 方法插入new_string_toinsert = soup.new_string("10000")new_div_number_tag.insert(0,new_string_toinsert)print producer_entries.prettify()            
發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 黄梅县| 吉安县| 历史| 邵武市| 张家界市| 隆林| 元谋县| 利津县| 淮南市| 尼玛县| 包头市| 邹城市| 新竹市| 临潭县| 靖西县| 漳平市| 子长县| 积石山| 临澧县| 黑河市| 麻阳| 友谊县| 黔东| 临邑县| 定结县| 天镇县| 太仓市| 曲沃县| 夏津县| 台前县| 普洱| 隆林| 普安县| 平武县| 汶上县| 晴隆县| 佛冈县| 福海县| 比如县| 都江堰市| 积石山|