gpt4 book ai didi

当我想要一个时,Python 到 CSV 将字符串分成两列

转载 作者:太空宇宙 更新时间:2023-11-03 11:22:35 25 4
gpt4 key购买 nike

我正在用 BeautifulSoup 抓取一个页面,部分逻辑是有时 <td> 的部分内容标签可以有一个 <br>在里面。

所以有时它看起来像这样:

<td class="xyz">
text 1
<br>
text 2
</td>

有时它看起来像这样:

<td class="xyz">
text 1
</td>

我正在遍历这个并添加到我最终添加到列表列表的 output_row 列表。无论我看到前一种格式还是后者,我都希望文本位于一个单元格中。

我找到了一种方法来确定我是否看到了 <br>标记,因为 td.string 显示为无,而且我也知道文本 2 中始终包含“ABC”。所以:

    elif td.string == None:
if 'ABC' in td.contents[2]:
new_string = td.contents[0] + ' ' + td.contents[2]
output_row.append(new_string)
print(new_string)
else:
#this is for another situation and it works fine

当我在 Jupyter Notebook 中打印它时,它显示为一行“文本 1 文本 2”。但是当我打开我的 CSV 时,它位于两个不同的列中。因此,当 td.string 包含内容(意味着没有 <br> 标记)时,文本 1 显示在一列中,但是当我到达具有 <br> 的部分时标签,我所有的数据都被转移了。

我不确定为什么在将它们连接到列表之前将它们显示为两个不同的字符串(两列)。

我正在这样写文件:

with open('C:/location/file.csv', 'w',newline='') as csv_file:
writer=csv.writer(csv_file,delimiter=',')
#writer.writerow(headers)
for row in output_rows:
writer.writerow(row)

csv_file.close

最佳答案

您可以使用 get_text() 处理这两种情况带有“strip”和“separator”:

from bs4 import BeautifulSoup

dat="""
<table>
<tr>
<td class="xyz">
text 1
<br>
text 2
</td>

<td class="xyz">
text 1
</td>
</tr>
</table>
"""

soup = BeautifulSoup(dat, 'html.parser')
for td in soup.select("table > tr > td.xyz"):
print(td.get_text(separator=" ", strip=True))

打印:

text 1 text 2
text 1

关于当我想要一个时,Python 到 CSV 将字符串分成两列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39902832/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com