在“生活很復雜”的幫助下,我設法從 CNN 新聞網站上抓取了資料。從中提取的資料 (URL) 保存在 .csv 檔案 (test1) 中。請注意,這是手動完成的,因為它更容易做到!
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
with open('test1.csv', 'r') as file:
csv_file = file.readlines()
for url in csv_file:
try:
article = Article(url.strip(), config=config)
article.download()
article.parse()
print(article.title)
article_text = article.text.replace('\n', ' ')
print(article.text)
except ArticleException:
print('***FAILED TO DOWNLOAD***', article.url)
with open('test2.csv', 'a', newline='') as csvfile:
headers = ['article title', 'article text']
writer = csv.DictWriter(csvfile, lineterminator='\n', fieldnames=headers)
writer.writeheader()
writer.writerow({'article title': article.title,
'article text': article.text})
使用上面的代碼,我設法從 URL 中抓取實際的新聞資訊(標題和內容)并將其匯出到 .csv 檔案。匯出的唯一問題是它只匯出最后一個標題和文本(因此我認為它會不斷覆寫第一行的資訊)
如何獲取 csv 檔案中的所有標題和內容?
uj5u.com熱心網友回復:
謝謝你給我一個呼喊。
下面的代碼應該可以幫助您解決 CSV 寫入問題。如果它不只是讓我知道,我會修改我的答案。
PS 我將更新我的Newspaper3k 概述檔案,其中包含有關撰寫 CSV 檔案的更多詳細資訊。
PPS 我目前正在撰寫一個新的新聞抓取工具,因為 Newspaper3k 的開發已經死了。我不確定我的代碼的發布日期。
import csv
from newspaper import Config
from newspaper import Article
from os.path import exists
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
urls = ['https://www.cnn.com/2021/10/25/tech/facebook-papers/index.html', 'https://www.cnn.com/entertainment/live-news/rust-shooting-alec-baldwin-10-25-21/h_257c62772a2b69cb37db397592971b58']
for url in urls:
article = Article(url, config=config)
article.download()
article.parse()
article_meta_data = article.meta_data
published_date = {value for (key, value) in article_meta_data.items() if key == 'pubdate'}
article_published_date = " ".join(str(x) for x in published_date)
file_exists = exists('cnn_extraction_results.csv')
if not file_exists:
with open('cnn_extraction_results.csv', 'w', newline='') as file:
headers = ['date published', 'article title', 'article text']
writer = csv.DictWriter(file, delimiter=',', lineterminator='\n', fieldnames=headers)
writer.writeheader()
writer.writerow({'date published': article_published_date,
'article title': article.title,
'article text': article.text})
else:
with open('cnn_extraction_results.csv', 'a', newline='') as file:
headers = ['date published', 'article title', 'article text']
writer = csv.DictWriter(file, delimiter=',', lineterminator='\n', fieldnames=headers)
writer.writerow({'date published': article_published_date,
'article title': article.title,
'article text': article.text})
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/337207.html
下一篇:在CSV檔案的打開行中寫入
