【问题标题】:Save body text on csv file | Python 3将正文保存在 csv 文件中 |蟒蛇 3
【发布时间】:2016-10-30 18:11:43
【问题描述】:

我正在尝试创建一个包含几篇文章的数据库,用于文本挖掘。 我通过网络抓取提取正文,然后将这些文章的正文保存在 csv 文件中。但是,我无法保存所有正文。 我想出的代码只保存最后一个 URL(文章)的文本,而如果我打印我正在抓取的内容(以及我应该保存的内容),我会获得所有文章的正文。

我只是从列表中包含了一些 URL(其中包含大量 URL),只是为了给你一个想法:

import requests
from bs4 import BeautifulSoup
import csv

r=["http://www.nytimes.com/2016/10/12/world/europe/germany-arrest-syrian-refugee.html",
"http://www.nytimes.com/2013/06/16/magazine/the-effort-to-stop-the-    attack.html",
"http://www.nytimes.com/2016/10/06/world/europe/police-brussels-knife-terrorism.html",
"http://www.nytimes.com/2016/08/23/world/europe/france-terrorist-attacks.html",
"http://www.nytimes.com/interactive/2016/09/09/us/document-Review-of-the-San-Bernardino-Terrorist-Shooting.html",
]

for url in r:
    t= requests.get(url)
    t.encoding = "ISO-8859-1"
    soup = BeautifulSoup(t.content, 'lxml')
    text = soup.find_all(("p",{"class": "story-body-text story-content"}))
    print(text)
with open('newdb30.csv', 'w', newline='') as csvfile:
    spamwriter = csv.writer(csvfile, delimiter=' ',quotechar='|', quoting=csv.QUOTE_MINIMAL)
    spamwriter.writerow(text)

【问题讨论】:

    标签: python csv web screen-scraping


    【解决方案1】:

    尝试在 for 循环之前声明变量,例如 all_text = "",并在 for 循环结束时通过 all_text += text + "\n"text 添加到 all_text\n 创建一个新行)。

    然后,在最后一行中,不要写text,而是写all_text

    【讨论】:

    • TypeError:只能将列表(而不是“str”)连接到列表。所以我在 str(text)+ "\r\n" 中编辑它。现在它似乎正在工作,输出是这样的: d a t a - t o t a l - c o u n t = " 6 5 5 2 " > M r 。 | |事件 | |我是 | |不 | | s ü r e | |什么时候 | | — | |或 | | e v e n | |如果 |关于如何使其更具可读性的任何提示?
    • 你在 for 循环之前做了all_text = []all_text = "" 吗?应该是第二个。
    • 我按照建议使用了第二个 all_text = ""。通过添加 str(text) 我解决了错误,但我得到一个难以阅读的输出。
    • 我明白了。您可以通过执行例如添加仅列表的元素all_text += text[0] + "\n" 如果你只想写第一个元素。您还可以通过 all_text += text[0] + "\n---\n" 在每个页面文本之间添加分隔线
    猜你喜欢
    • 2022-06-13
    • 1970-01-01
    • 1970-01-01
    • 2018-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-17
    相关资源
    最近更新 更多