我有这个简单的html表:
<tr align="center" class="tableRow1Font" >
<td>OPEN</td>
<td>80002</td>
<td>
<span style="font-weight:bold;">
ACCY
</span>
<A HREF="http://bulletin.gwu.edu/search/?P=ACCY+2001" target="_blank">
<span style="font-weight:bold;">
2001
</span>
</A>
</td>
<td>10</td>
<td>Intro Financial Accounting</td>
<td>3.00</td>
<td> Ray, K</td>
<td><a href="http://virtualtour.gwu.edu/#MON" target="_blank" >MON</a> 113</td>
<td>MW<br>12:45PM - 02:00PM</td>
<td>08/25/14 - 12/06/14</td>
<td>
</td>
</tr>
我正在使用Python的xpath和请求。使用xpath函数,我将如何提取所有&#39; td&#39;这个表格中的标题用逗号分隔?
我希望提取的数据如下所示:
OPEN, 80002, ACCY 2001, 10, Intro to Financial Accounting, 3.00, Ray, K, MW 12:45-02:00PM
答案 0 :(得分:1)
试试这个:
<强>代码:强>
src = """<tr align="center" class="tableRow1Font" >
<td>OPEN</td>
<td>80002</td>
<td>
<span style="font-weight:bold;">
ACCY
</span>
<A HREF="http://bulletin.gwu.edu/search/?P=ACCY+2001" target="_blank">
<span style="font-weight:bold;">
2001
</span>
</A>
</td>
<td>10</td>
<td>Intro Financial Accounting</td>
<td>3.00</td>
<td> Ray, K</td>
<td><a href="http://virtualtour.gwu.edu/#MON" target="_blank" >MON</a> 113</td>
<td>MW<br>12:45PM - 02:00PM</td>
<td>08/25/14 - 12/06/14</td>
<td>
</td>
</tr>"""
from lxml import html
tree = html.fromstring(src)
tds = tree.xpath("//td/descendant-or-self::*/text()[normalize-space()]")
print ", ".join([td.strip() for td in tds])
<强>结果:强>
OPEN, 80002, ACCY, 2001, 10, Intro Financial Accounting, 3.00, Ray, K, MON, 113, MW, 12:45PM - 02:00PM, 08/25/14 - 12/06/14
[Finished in 0.5s]
请注意,这会从所有td
标记中获取所有文本,包括<a>
子节点内的标记,即。 MON
。
清理结果取决于您。