o1-mini-2024-09-12· OpenAI
WildChat-4.8M (AI2)
google 新聞爬蟲 ##用python,時間間區為2024/11/01-2024/11/17 ##爬取 台積電 相關新聞
- User
google 新聞爬蟲 ##用python,時間間區為2024/11/01-2024/11/17 ##爬取 台積電 相關新聞
- Assistant
google 新聞爬蟲 ##用python,時間間區為2024/11/01-2024/11/17 ##爬取 台積電 相關新聞
要使用 Python 爬取 Google 新聞中與「台積電」相關、且發布日期介於 2024/11/01 至 2024/11/17 的新聞,你可以使用 GoogleNews 這個 Python 套件。以下是詳細的步驟和範例程式碼。
首先,確保你已經安裝了 GoogleNews 和 pandas 套件。你可以使用 pip 來安裝這些套件:
pip install GoogleNews
pip install pandas
以下是使用 GoogleNews 爬取相關新聞的範例程式碼:
from GoogleNews import GoogleNews
import pandas as pd
def scrape_tsmc_news(start_date, end_date, query="台積電", lang="zh-TW"):
"""
爬取指定日期範圍內與台積電相關的新聞。
:param start_date: 開始日期,格式為 'YYYY/MM/DD'
:param end_date: 結束日期,格式為 'YYYY/MM/DD'
:param query: 搜尋關鍵字,預設為 '台積電'
:param lang: 語言設定,預設為 'zh-TW' 繁體中文
:return: 包含新聞標題、媒體、日期、連結的 DataFrame
"""
googlenews = GoogleNews(lang=lang, region='TW')
googlenews.set_time_range(start_date, end_date)
googlenews.search(query)
# 取得搜尋結果的所有頁面
news = []
while True:
current_page = googlenews.page_at
results = googlenews.results()
if not results:
break
news.extend(results)
googlenews.getpage(current_page + 1)
# 關閉搜尋
googlenews.clear()
# 整理資料
df = pd.DataFrame(news)
return df
if __name__ == "__main__":
# 設定日期範圍
start = '2024/11/01'
end = '2024/11/17'
# 爬取新聞
tsmc_news = scrape_tsmc_news(start, end)
# 顯示結果
print(tsmc_news)
# 將結果存成 CSV 檔案
tsmc_news.to_csv('tsmc_news_20241101_20241117.csv', index=False, encoding='utf-8-sig')
導入套件:
GoogleNews:用於搜尋 Google 新聞。pandas:用於資料整理和存儲。函數 scrape_tsmc_news:
'YYYY/MM/DD'。'zh-TW',地區為台灣 'TW'。set_time_range 方法設定日期範圍。search 方法進行關鍵字搜尋。while 迴圈抓取所有分頁的結果,直到沒有更多結果為止。pandas 的 DataFrame 便於後續處理。主程式:
scrape_tsmc_news 函數取得新聞資料。合法性與道德性:在進行網路爬蟲時,請務必遵守相關網站的 robots.txt 規範,以及相關法律法規。頻繁的請求可能會對目標網站造成負擔,建議設定合理的請求間隔。
套件限制:GoogleNews 套件並非官方的 Google 新聞 API,可能會有功能限制或不穩定的情況。如果需要更穩定的服務,建議考慮使用官方的 Google Custom Search API 或其他第三方新聞 API(如 NewsAPI)。
日期格式:確保輸入的日期格式正確,否則可能會導致搜尋結果不如預期。
未來日期:根據你的需求,你設定的日期範圍在 2024 年 11 月。請確保在該日期範圍內執行爬蟲,否則可能無法取得任何結果。
你可以根據需要擴展此爬蟲,例如:
schedule 或 cron 等工具,定期執行爬蟲以取得最新新聞。希望這個範例能夠幫助你順利完成爬取台積電相關新聞的任務!
Not yet included in a published release.