Python - beautifulsoup输出到csv只显示1条记录

问题描述 投票:1回答:1

问题:当我打印数据以查看其结构时,它很好。但是当我输出到csv我只得到最后一个记录,其中每个字符逐行分开而不是所有记录。

例如:Python代码输出:

johnsmith123jghoststreet902231131
laracroft23jghoststreet902231131
janecone23jghoststreet902231131

当我输出到csv它显示

j

a

n

e

c

o

等......只是最后的记录

这是代码

import urllib.request, urllib.parse, urllib.error
from bs4 import BeautifulSoup
import ssl
import csv
#ignore SSL errors
ctx=ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE


html = urllib.request.urlopen("https://www.omielife.com/pages/retailers"
,context=ctx).read().decode('utf-8')
soup=BeautifulSoup(html,'html.parser')

links= soup.find_all('p')
print(links)
#a_data = soup.find_all(class_='p') #itemprop="streetaddress"> address </span>
for item in links:
    print(item.text, sep=' ', end='\n', flush=True)
    a=item.text


with open('test2.csv','w') as fp:
    writer = csv.writer(fp)
    writer.writerows(a)
python csv export-to-csv
1个回答
0
投票

在Python中,字符串列表和单个字符串都是可迭代的。在您的代码中,a是一个单独的字符串。但是你把它传递给需要多个字符串的writerows()

你应该在多个字符串的a中建立一个列表 - 然后writerows()会做你期望的。

© www.soinside.com 2019 - 2024. All rights reserved.