2015-09-16 36 views
3

我使用Python 3.4與lxml.html庫。python lxml:用於有選擇地刪除內聯樣式屬性的語法?

我想從我使用CSS選擇器定位的html元素中刪除border-bottom內聯樣式。

這裏顯示出一個樣品TD元素和我選擇一個代碼片段:

html_snippet = lxml.html.fromstring("""<td valign="bottom" colspan="10" align="center" style="background-color:azure; border-bottom:1px solid #000000"><font style="font-family:Times New Roman" size="2">Estimated Future Payouts</font> \n   <br/><font style="font-family:Times New Roman" size="2">Under Non-Equity Incentive</font> \n   <br/><font style="font-family:Times New Roman" size="2">Plan Awards</font> \n  </td>""") 
selection = html_snippet.cssselect('td[style*="border-bottom"]') 
selection.attrib['style'] 
>>>>'background-color: azure;border-bottom:1px solid #000000' 

什麼是訪問內嵌樣式屬性,所以我可以從我的目標的任何元素刪除border-bottom屬性的正確方法我選擇?

回答

3

您可以通過拆分style屬性值由;接近它,創建一個CSS屬性的名稱 - >值地圖,從地圖中刪除的border-bottom並通過與;加入地圖的元素,再次重建style屬性。示例實現:

style = selection.attrib['style'] 
properties = dict([item.split(":") for item in style.split("; ")]) 

del properties['border-bottom'] 

selection.attrib['style'] = "; ".join([key + ":" + value for key, value in properties.items()]) 

print(lxml.html.tostring(selection)) 

我很確定您可以輕鬆打破此解決方案。


另外,這裏有一個「瘋狂」的選項 - 轉儲數據變成「HTML」文件,通過selenium打開瀏覽器中的文件,通過javascript刪除屬性,並打印出的HTML表示元件之後:

import os 
from selenium import webdriver 

data = """ 
<td valign="bottom" colspan="10" align="center" style="background-color:azure; border-bottom:1px solid #000000"><font style="font-family:Times New Roman" size="2">Estimated Future Payouts</font> \n   <br/><font style="font-family:Times New Roman" size="2">Under Non-Equity Incentive</font> \n   <br/><font style="font-family:Times New Roman" size="2">Plan Awards</font> \n  </td> 
""" 
with open("index.html", "w") as f: 
    f.write("<body><table><tr>%s</tr></table></body>" % data) 

driver = webdriver.Chrome() 
driver.get("file://" + os.path.abspath("index.html")) 

td = driver.find_element_by_tag_name("td") 
driver.execute_script("arguments[0].style['border-bottom'] = '';", td) 

print(td.get_attribute("outerHTML")) 

driver.close() 

打印:

<td valign="bottom" colspan="10" align="center" style="background-color: rgb(240, 255, 255);"><font 
     style="font-family:Times New Roman" size="2">Estimated Future Payouts</font> 
    <br><font style="font-family:Times New Roman" size="2">Under Non-Equity Incentive</font> 
    <br><font style="font-family:Times New Roman" size="2">Plan Awards</font> 
</td> 
+0

謝謝!對於其他人,請注意alecxe第一個答案中的dict items方法是python 2 .iteritems而不是python 3 .items – deseosuho

+0

@deseosuho oops,是的,是固定的。謝謝! – alecxe

2

沒有爲一個包,儘管矯枉過正在這種情況下。

import cssutils 
sheet = cssutils.parseStyle('background-color: azure;border-bottom:1px solid #000000') 
sheet.removeProperty('border-bottom') # returns '1px solid #000' 
print(sheet.cssText) 

輸出background-color: azure

+0

很好找!我認爲這是目前最簡單的選擇。 – alecxe