我正在尝试使用 lxml 解析 HTML 表。在rows = outhtml.xpath('//tr/td/span[@class="boldred"]/text()')
获取结果时,我试图仅在以我的配置文件中的变量开头时提取列内容。例如,如果 a<td>
以“Street 1”开头,那么我想获取该标签的<span>
内容。<td>
这样,我可以拥有一个元组的元组(负责处理 None 值),然后我可以将其存储在数据库中。
lxml_parse.py
import lxml.html as lh
doc=open('test.htm', 'r')
outhtml=lh.parse(doc)
doc.close()
rows = outhtml.xpath('//tr/td/span[@class="boldred"]/text()')
print rows
测试.htm
<tr>
<td></td>
<td colspan="2">
Street 1:<span class="required"> *</span><br />
<span class="boldred">2100 5th Ave</span>
</td>
<td colspan="2">
Street 2:<br />
<span class="boldred">Ste 202</span>
</td>
</tr>
<tr>
<td></td>
<td>
City:<span class="required"> *</span><br />
<span class="boldred">NYC</span>
</td>
<td>
State:<br />
<SPAN CLASS="boldred2"></SPAN><br/><SPAN CLASS="boldred">NY</SPAN>
</td>
<td>
Country:<span class="required"> *</span><br />
<SPAN CLASS="boldred2"></SPAN><br/><SPAN CLASS="boldred">USA</SPAN>
</td>
<td>
Zip:<br />
<span class="boldred">10022</span>
</td>
</tr>
输出 :
$ python lxml_parse.py
['2100 5th Ave', 'Ste 202', 'NYC', 'NY', 'USA', '10022']
解析一堆变量是我遇到的问题:
import lxml.html as lh
desiredvars = ['Street 1','Street 2','City', 'State', 'Zip']
doc=open('test.htm', 'r')
outhtml=lh.parse(doc)
doc.close()
myresultset = ((var, outhtml.xpath('//tr/td[child::*[text()=var]]/span[@class="boldred"]/text()')) for var in desiredvars)
print myresultset