【发布时间】:2019-11-23 14:50:28
【问题描述】:
我已经编写了漂亮的汤代码来创建以下格式的输出
Quatermass 2
Ghostbusters
Life of Brian
我现在想将其写入 csv 文件。但是,我熟悉的唯一 csv 写入函数是 write_row。当我使用它时,它只打印我抓取的最后一个“title_content”对象,即 ->Brian 的生活
我的python代码是
from bs4 import BeautifulSoup
import requests
import re
import csv
html = ['table.html']
with open("table.html", "r") as f:
contents = f.read()
outputfilename = 'row_writer.csv'
print(outputfilename)
outputfile = open(outputfilename, 'w') #wb = write and binary - indicates file open for writing in binary
writer = csv.writer(outputfile)
writer.writerow(['Title'])
soup = BeautifulSoup(contents, "lxml")
for name in soup.find_all("td", {"width": "41%"}, string=re.compile(r'^(?!Title$)')):
title_content = ((name).get_text())
print(title_content)
writer.write_row([title_content])
谁能帮忙将我的整个内容写入 csv 列?
HTML
<table width='100%' border='0' cellpadding='0' class='blackbg textheadtitle'>
<tr>
<td width='41%' align='left'>Title</td>
<table width='99%' border='0' cellpadding='1' class="normal">
<tr>
<td width='41%' align='left'><strong>Quatermass 2</strong></td>
<table width='100%' border='0' cellpadding='0' class='blackbg textheadtitle'>
<tr>
<td width='41%' align='left'>Title</td>
<table width='99%' border='0' cellpadding='1' class="normal">
<tr>
<td width='41%' align='left'><strong>Ghostbusters</strong></td>
<table width='100%' border='0' cellpadding='0' class='blackbg textheadtitle'>
<tr>
<td width='41%' align='left'>Title</td>
<table width='99%' border='0' cellpadding='1' class="normal">
<tr>
<td width='41%' align='left'><strong>Life of Brian</strong></td>
【问题讨论】:
-
写行的地方需要缩进,否则不在循环块中。缩进在 Python 中很重要。
-
太好了,谢谢彼得。尽管我的列数据现在打印为 Title、NULL、Quatermass 2、NULL、Ghostbusters、NULL、Life of Brian、NULL。我输出中的每个第二个单元格都是空白的。知道为什么吗?
-
用熊猫,很可爱
标签: python csv beautifulsoup writer