Python到CSV在我需要时将字符串拆分为两列

时间:2016-10-06 18:05:03

标签: python csv beautifulsoup

我正在使用BeautifulSoup抓取一个页面,部分逻辑是有时<td>标记的部分内容可能包含<br>

所以有时看起来像这样:

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

有时它看起来像这样:

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

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

我找到了一种方法来确定我是否看到<br>标签,因为td.string显示为无,我也知道文字2总是有&#39; ABC&#39;在里面。所以:

    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笔记本中打印时,它显示为&#34;文本1文本2&#34;作为一条线。但是当我打开我的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

1 个答案:

答案 0 :(得分:2)

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

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