【问题标题】:Python - beauitful soup output to csv only showing 1 recordPython - beautifulsoup 输出到 csv 仅显示 1 条记录
【发布时间】:2018-08-11 06:37:30
【问题描述】:

问题:当我打印数据以查看其结构时,它很好。但是当我输出到 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】:

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

    您应该在a 中建立一个包含多个字符串的列表——然后writerows() 将按照您的预期进行。

    【讨论】:

    • 您能否指出我如何做到这一点或为我提供示例?
    • @tabarneck:创建一个名为 a 的列表。将您所有的item.texts 附加到它。
    • 对于链接中的项目: print(item.text, sep=' ', end='\n', flush=True) a=item.text page_List=[] for page_data in a: page_List .append(page_data) print(page_List.text, sep=' ', end='\n', flush=True)
    • 它不喜欢列表中的 a.item.text。我收到一个错误“列表没有文字”
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-07-11
    • 1970-01-01
    • 1970-01-01
    • 2021-04-17
    • 1970-01-01
    • 1970-01-01
    • 2012-12-03
    相关资源
    最近更新 更多