我有一个存储在文件中的HTML表。我想从具有如下属性的表中获取每个td值:
<td describedby="grid_1-1" ... >Value for CSV</td>
<td describedby="grid_1-1" ... >Value for CSV2</td>
<td describedby="grid_1-1" ... >Value for CSV3</td>
<td describedby="grid_1-2" ... >Value for CSV4</td>
我希望将其放入CSV文件中,每个新值都会占用CSV中的新行。
因此,对于上面的文件,生成的CSV将是:
Value for CSV
Value for CSV2
Value for CSV3
CSV4的值将被忽略,如=“grid_1-2”所述,而不是“grid_1-1”。
所以我尝试了这个,但无论我怎样尝试,似乎都有 (a)每条印刷线之间的空白行 (b)用逗号分隔每个字符。
所以印刷更像是:
V,a,l,u,e,f,o,r,C,S,V,
V,a,l,u,e,f,o,r,C,S,V,2
我现在做了什么傻事?
谢谢:)
import csv
import os
from bs4 import BeautifulSoup
with open("C:\\Users\\ADMIN\\Desktop\\test.html", 'r') as orig_f:
soup = BeautifulSoup(orig_f.read())
results = soup.findAll("td", {"describedby":"grid_1-1"})
with open('C:\\Users\\ADMIN\\Desktop\\Deploy.csv', 'wb') as fp:
a = csv.writer(fp, delimiter=',')
for result in results :
a.writerows(result)
答案 0 :(得分:3)
如果result是列表中的字符串,则需要将其包装在列表中,因为writerows需要迭代迭代并迭代字符串:
a.writerows([result]) <- wrap in a list
在您的情况下,您应该使用writerow并从结果中的每个td标记中提取文本:
a.writerow([result.text]) # write the text from td element
您的结果列表中包含所有td标记,因此您只需要使用.text。
提取文本答案 1 :(得分:1)
使用lxml
和csv
模块。
td
文字值,其中describedby
属性值为grid_1-1
lxml的xpath()
方法。csv
文件。writerow()
方法代码:
content = """
<body>
<td describedby="grid_1-1">Value for CSV</td>
<td describedby="grid_1-1">Value for CSV2</td>
<td describedby="grid_1-1">Value for CSV3</td>
<td describedby="grid_1-2">Value for CSV4</td>
</body>
"""
from lxml import etree
import csv
root = etree.fromstring(content)
l = root.xpath("//td[@describedby='grid_1-1']/text()")
with open('/home/vivek/Desktop/output.csv', 'wb') as fp:
a = csv.writer(fp, delimiter=',')
for i in l :
a.writerow([i, ])
输出:
Value for CSV
Value for CSV2
Value for CSV3
Value for CSV4