【问题标题】:Writing to csv file outputs every letter in its own cell写入 csv 文件会输出其自己单元格中的每个字母
【发布时间】:2019-07-16 12:38:15
【问题描述】:
import bs4 as bs
import urllib.request
import csv

source = 
   urllib.request.urlopen('http://www.thebest100lists.com/best100actors/').read()

soup = bs.BeautifulSoup(source, 'lxml')

for paragraph in soup.find_all('ol'):
    celebList = paragraph.text
    print(celebList)

with open('celebList.csv', 'w', newline='') as f:
    writer = csv.writer(f)

writer.writerow[soup.title.string]
for i in celebList:
    writer.writerow([i])

我正在使用漂亮的汤 4 从网站上的列表中抓取数据以将其输出到 .csv 文件。我已经正确地抓取了我正在寻找的数据,但是当我保存运行程序时,csv 文件的每一行都有自己的单元格中的每个字母。我尝试将数据转换为字符串,还尝试将 (i) 放在方括号中,但它对我没有用。

【问题讨论】:

  • 你想要的 csv 输出格式是什么?

标签: python web-scraping export-to-csv


【解决方案1】:

你迭代 celebList 中的文本而不是列表。

你可能想做类似的事情

celebList = []
for paragraph in soup.find_all('ol'):
    celebList.append(paragraph.text)

【讨论】:

    【解决方案2】:

    你可以这样做:

    celeblistsplit=celebList.split('\n')
    celeblistsplit
    

    然后:

    f=open('output.csv','w')
    for each in celeblistsplit:
        if len(each)>0:
            f.write(each)
            f.write(',')
            f.write('\n')
    f.close()
    

    生成的文件:

    Robert De Niro,
    Al Pacino,
    Tom Hanks,
    Johnny Depp,
    Jack Nicholson,
    Marlon Brando,
    Meryl Streep,
    Leonardo DiCaprio,
    ...
    

    【讨论】:

      【解决方案3】:
      import bs4 as bs
      import urllib.request
      import csv
      
      source = urllib.request.urlopen('http://www.thebest100lists.com/best100actors/').read()
      
      soup = bs.BeautifulSoup(source, 'lxml')
      
      celebList = []     # an empty list to store the text
      for paragraph in soup.find_all('ol'):
          celebList.append(paragraph.text)
          # print(celebList)
      
      # file writing
      # print(celebList) # ["\nRobert De Niro\n\nAl Pacino\n\nTom Hanks\n\nJohnny .. ] 
      celebList = map(lambda s: s.strip(), celebList)   # removing the leading spaces in the list
      celebList = list(celebList)
      
      
      with open('celebList.csv', 'w') as file:
          for text in celebList:
              file.write(text)
      

      输出:

      Robert De Niro
      
      Al Pacino
      
      Tom Hanks
      
      Johnny Depp
      
      Jack Nicholson
      
      Marlon Brando
      
      .
      .
      .
      

      【讨论】:

      • 嘿!感谢您的深入回复。我可以看到我哪里出错了。但是,我可能看错了地方,但是当我在运行该文件后打开该文件时,它不会向 .csv 文件输出任何内容。你知道为什么吗?
      • @AlanPiggott 尝试删除 csv 文件并再次运行代码。
      • 它现在给了我这个错误:文件“C:/Users/Alan/PycharmProjects/untitled/venv/Web scraper.py”,第 14 行,在 中,带有 open('celebList.csv ', 'w', newline='') as f: PermissionError: [Errno 13] Permission denied: 'celebList.csv'
      • @AlanPiggott 可能文件已打开。先关闭再删除。之后,运行代码来创建它。
      • 还是没有运气。我尝试重命名、删除它,甚至在 Excel 中打开 office.com 上的文件,但没有写入任何内容。当我在 PyCharm 中打开 csv 文件时,它似乎都正确,所以我不明白发生了什么。也许它是某种错误。
      【解决方案4】:

      我认为使用 a 标签的类选择器来获得一个没有间隙的列表然后用 pandas 转储到 csv 会更有效

      from bs4 import BeautifulSoup
      import requests
      import pandas as pd
      
      url = 'http://www.thebest100lists.com/best100actors/'
      res = requests.get(url)
      soup = BeautifulSoup(res.content, "lxml")
      names = [name.text for name in soup.select('a.class1')]
      df = pd.DataFrame(names,columns=['Names'])
      df.to_csv(r'C:\Users\User\Desktop\Celebs.csv', sep=',', encoding='utf-8',index = False )
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-12-11
        • 2021-01-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-08-18
        • 1970-01-01
        相关资源
        最近更新 更多