【问题标题】:How to fix writing to csv file如何修复写入 csv 文件的问题
【发布时间】:2019-10-19 14:04:23
【问题描述】:

我希望我的程序将文章日期、标题和正文写入 csv 文件。当我在控制台中打印正文时,它会打印所有内容,但是在 csv 文件上,它只打印文章的最后一行。

CSV 结果:

控制台打印:

我尝试将日期、标题和正文文本写入单独的代码行中的行中,并作为列表并置,结果相同。

from bs4 import BeautifulSoup
from urllib.request import urlopen
import csv

csvfile = "C:/Users/katew/Dropbox/granularitygrowth/Politico/pol.csv"
with open(csvfile, mode='w', newline='') as pol:
    csvwriter = csv.writer(pol, delimiter='|', quoting=csv.QUOTE_MINIMAL)
    csvwriter.writerow(["Date", "Title", "Article"])

    #for each page on Politico archive
    for p in range(0,1):
        url = urlopen("https://www.politico.com/newsletters/playbook/archive/%d" % p)
        content = url.read()

        #Parse article links from page
        soup = BeautifulSoup(content,"lxml")
        articleLinks = soup.findAll('article', attrs={'class':'story-frag format-l'})

        #Each article link on page
        for article in articleLinks:
            link = article.find('a', attrs={'target':'_top'}).get('href')

            #Open and read each article link
            articleURL = urlopen(link)
            articleContent = articleURL.read()

            #Parse body text from article page
            soupArticle = BeautifulSoup(articleContent, "lxml")

            #Limits to div class = story-text tag (where article text is)
            articleText = soupArticle.findAll('div', attrs={'class':'story-text'})
            for div in articleText:

                #Find date
                footer = div.find('footer', attrs={'class':'meta'})
                date = footer.find('time').get('datetime')
                print(date)

                #Find title
                headerSection = div.find('header')
                title = headerSection.find('h1').text
                print(title)

                bodyText = div.findAll('p')
                for p in bodyText:
                    p_string = str(p.text)
                    textContent = "" + p_string
                    print(textContent)

                #Adds data to csv file
                csvwriter.writerow([date, title, textContent])

我希望 csv 文件包含日期、标题和全文。

【问题讨论】:

    标签: python csv beautifulsoup export-to-csv


    【解决方案1】:

    问题出在您的for p in bodyText: 循环中。您将最后一个 p 的文本分配给您的 textContent 变量。尝试类似:

    textContent = ""
    bodyText = div.findAll('p')
    for p in bodyText:
        p_string = str(p.text)
        textContent += p_string + ' '
    
    print(textContent)
    csvwriter.writerow([date, title, textContent])
    

    【讨论】:

    • 谢谢!这正是我需要的答案。
    猜你喜欢
    • 2021-05-07
    • 2016-05-21
    • 2015-12-10
    • 2021-12-29
    • 1970-01-01
    • 1970-01-01
    • 2018-03-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多