【发布时间】:2018-11-06 02:51:07
【问题描述】:
我想从特定格式的链接中提取下面的 HTML 表格内容。
网页上的 HTML 代码:
<table>
<thead>
<tr>
<th>name</th>
<th>brand</th>
<th>description</th>
</tr>
</thead>
<tbody>
<tr>
<td><a href="http://abcd.com"><span style="color: #000; min-width: 160px;">abcd</span></a></td>
<td><a href="http://abcd.com" target="_blank"><span style="color: #000;">abcd123</span></a></td>
<td><a href="http://abcd.com" target="_blank"><span style="color: #000;">abcd 123 (1g)</span></a><br/></td>
</tr>
<tr>
<td><a href="http://efgh.com" target="_blank"><span style="color: #000; min-width: 160px;">efgh</span></a></td>
<td><a href="http://efgh.com" target="_blank"><span style="color: #000;">efgh456</span></a></td>
<td><a href="http://efgh.com" target="_blank"><span style="color: #000;">efgh 456 (2g)</span></a><br/></td>
</tr>
<tr>
<td><a href="http://ijkl.com" target="_blank"><span style="color: #000; min-width: 160px;">ijkl</span></a></td>
<td><a href="http://ijkl.com" target="_blank"><span style="color: #000;">ijkl789</span></a></td>
<td><a href="http://ijkl.com" target="_blank"><span style="color: #000;">ijkl 789 (3g)</span></a><br/></td>
</tr>
</tbody>
</table>
CSV 文件中所需的输出格式如下:
链接、名称、品牌、描述
http://abcd.com,abcd,abcd123,abcd123 (1g)
http://efgh.com,efgh,efgh456,efgh456 (2g)
http://ijkl.com,ijkl,ijkl789,ijkl789 (3g)
下面是我的代码:
rows = doc.xpath("//table")
for tr in rows:
tds = tr.xpath("//td")
for td in tds:
Link = td.xpath("//td[1]/a/@href")
name = td.xpath("//td[1]//text()")
brand = td.xpath("//td[2]//text()")
description = td.xpath("//td[3]//text()")
results = []
results.append(Link)
results.append(name)
results.append(brand)
results.append(description)
for result in results:
writer.writerow(result)
在这里,我不知道如何在 CSV 中获取上述特定格式的数据。
【问题讨论】:
标签: python csv beautifulsoup lxml