lxml中属性和样式标记之间的区别

时间:2009-09-29 03:41:45

标签: python lxml

我在尝试使用BeautifulSoup后学习lxml。但是,我不是一般的强大程序员。

我在一些源代码html中有以下代码:

<p style="font-family:times;text-align:justify"><font size="2"><b><i> The reasons to eat pickles include:  </i></b></font></p>

因为文本是粗体,我想拉那个文本。我似乎无法区分该特定线是否加粗。

当我今晚开始这项工作时,我正在处理一个文件,该文件在风格中具有粗体字,如下所示:

<p style="font-style:italic;font-weight:bold;margin:0pt 0pt 6.0pt;text-indent:0pt;"><b><i><font size="2" face="Times New Roman" style="font-size:10.0pt;">The reason I like tomatoes include:</font></i></b></p>

我应该说我正在处理的文档是一个片段,我在行中读取,将这些行连接起来然后使用html.fromstring函数

txtFile=open(r'c:\myfile.htm','r').readlines()
strHTM=''.join(txtFile)
newHTM=html.fromstring(strHTM)

所以我上面的第一行htm代码是newHTM [19]

嗯,这似乎让我更加接近

newHTM.cssselect('b')

我还没有完全理解,但这是解决方案:

for each in newHTM:
    if each.cssselect('b')
        each.text_content()

1 个答案:

答案 0 :(得分:0)

使用CSS API确实不是正确的方法。如果要查找所有b元素,请执行

strHTM=open(r'c:\myfile.htm','r').read() # no need to split it into lines first
newHTM=html.fromString(strHTM)
bELements = newHTM.findall('b')
for b in bElements:
    print b.text_content()
相关问题