您可以通過拆分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>
謝謝!對於其他人,請注意alecxe第一個答案中的dict items方法是python 2 .iteritems而不是python 3 .items – deseosuho
@deseosuho oops,是的,是固定的。謝謝! – alecxe