【发布时间】:2021-05-18 17:55:36
【问题描述】:
我有以下 python bode 生成两个列表作为输出。第一个列表是作者列表,我希望它出现在第二列(相当于 Excel 中的 B 列),第二个列表是标题列表,我希望它出现在第三列(C 列)中。控制台中的当前输出是这样的:
***FAILED TO DOWNLOAD*** http://grupodyasa.com/14-gauge-qvb0w/pipsc-collective-agreement-2019.html,
28 contents successfully fetched,
1 failed to fetch
目前有3个错误:
- 它们都在一个列中(Excel 中的 A 列)
- 标题与后续字母写在同一列,每个字母占一行/行。
- 我希望异常的统计信息应该反映在文件中(在每一行的末尾):1.当代码没有获取作者姓名时,2.当代码没有获取标题时),3.上面所有当代码没有从 URL 下载任何东西时。
我的代码如下:
from newspaper import Config
from newspaper import Article
from newspaper import ArticleException
import csv
USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:78.0) Gecko/20100101 Firefox/78.0'
config = Config()
config.browser_user_agent = USER_AGENT
config.request_timeout = 10
file1 = open('laborAuthorTitle4.csv', 'w')
w = csv.writer(file1)
count1=0
failCount=0
titleFail=0
authorFail=0
article_authors=[]
row1=[]
with open('laborURL29.csv', 'r') as file:
csv_file = file.readlines()
for url in csv_file:
try:
article = Article(url.strip(), config=config)
article.download()
article.parse()
article_authors=article.authors
for persons in article_authors:
try:
my_row = []
my_row.append(persons)
w.writerow(my_row)
except ArticleException:
print('***FAILED TO FETCH AUTHOR***', article.url)
authorFail=authorFail+1
print('Total fails', authorFail)
article_titles=article.title
for thema in article_titles:
try:
my_row2 = []
my_row2.append(thema)
w.writerow(my_row2)
except ArticleException:
print('***FAILED TO EXTRACT A TITLE***', article.url)
titleFail=titleFail+1
print('Total fails', titleFail)
count1=count1+1
except ArticleException:
print('***FAILED TO DOWNLOAD***', article.url)
failCount=failCount+1
file1.close()
print(count1, " contents successfully fetched")
print(failCount, "failed to fetch ")
创建/写入的 csv 文件在这里laborAuthors11
这是开头的截图:
【问题讨论】:
-
我无法运行您的代码,但从生成的 CSV 文件来看,您似乎在传递
writerow()一个字符串作为参数,而不是list— 所以它会解释每个 字符串的字符作为单独的行。 -
您是否查看了我之前与您分享的概览文档中的保存提取的数据部分?我将介绍如何保存到 CSV、JSON、HTML 和数据帧。
-
@Lifeiscomplex,不,我没有注意到它的存在。我会检查的。
标签: python csv format row write