Как исправить запись в CSV-файл - PullRequest
0 голосов
/ 04 июня 2019

Я хочу, чтобы моя программа записывала даты статей, заголовки и основной текст в CSV-файл. Когда я печатаю основной текст в консоли, он печатает все, однако в файле csv он печатает только последнюю строку статьи.

CSV Результат:

enter image description here

Печать консоли:

enter image description here

Я пытался записать дату, заголовок и основной текст в строки в отдельных строках кода, как в виде списка, и он дал тот же результат.

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-файл будет содержать дату, заголовок и полный текст.

1 Ответ

2 голосов
/ 04 июня 2019

Проблема в вашем 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])
...