2016-10-17 55 views
0

我使用BeautifulSoup在我的html頁面上查找特定元素。 我想添加一個屬性「值」到這個元素並保存到原始的HTML。 我如何用Beautifulsoup做到這一點?現在我這樣做是爲了讓整個HTML,找到特定的元素:如何使用Beautifulsoup在輸入元素中添加屬性

static_map = opener.open('my_url') 
bs = BeautifulSoup(static_map.read()) 
title = bs.find("input", {"name":"title"}) 

標題是這樣的:

<input class="has-popover form-control" data-container="body" id="id_title" maxlength="255" name="title" type="text"/> 

我想在此輸入元素添加屬性:值 然後保存到最初的HTML。

然後,我將不得不將這作爲發佈請求發送。

回答

1

試試這個:

bs.find('input')['value'] = ''#Whatever you want the value to be. 

因爲bs.find返回一個字典,所以在dicionary使用標符號設置的項目。

+0

謝謝。但是,我怎樣才能定義這個值是爲「title」名稱的元素? – user1919

+0

嘗試'bs = BeautifulSoup('' )'因爲你確切知道元素是什麼樣子的。 – rassar

+0

或者'bs.find('title')['value'] =「」'會起作用。 – rassar

相關問題