我正在使用带有lxml.html库的python 3.4。
我正在尝试从我使用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
属性?
答案 0 :(得分:3)
您可以通过style
将;
属性值拆分为border-bottom
来创建CSS属性名称 - &gt;值地图,从地图中移除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))
属性。示例实施:
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()
我很确定你可以轻松破解这个解决方案。
或者,这是一个相当&#34;疯狂&#34;选项 - 将数据转储到&#34; html&#34;文件,通过selenium
在浏览器中打开文件,通过javascript删除该属性,然后打印出该元素的HTML表示:
<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>
打印:
import paramiko
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(host, port, username=username, password=password)
stdin, stdout, stderr = client.exec_command('ls -l')
print stdout.read()
答案 1 :(得分: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