iT邦幫忙

2024 iThome 鐵人賽

DAY 23
0
AI/ ML & Data

【AI筆記】30天從論文入門到 Pytorch 實戰系列 第 23

【AI筆記】30天從論文入門到 Pytorch 實戰:使用API進行數據獲取 Day 22

  • 分享至 

  • xImage
  •  

本章節可以在colab上面跑。
主要是利用google search去抓相關新聞資訊,沒有爬各式網站種類。

Google 官方 API

我有先在 Google Search 設定查詢網址
https://jumping-code.com/2021/05/27/google-search-console-api-%E6%95%99%E5%AD%B8/
最近 Google 又改版了,所以只能自己 debug 了/images/emoticon/emoticon17.gif

這段程式碼使用 Google 的 Custom Search API 來進行搜尋,並將結果存儲在一個列表中。
每個結果包含標題和摘要。

提供的程式碼是用來進行 Google 搜尋的,以下是詳細解釋:
以下需要變更為自己的 API 和 ID

SEARCH_API = "*****************************"
SEARCH_ENGINE_ID = "**************"

因為有時候會查不到資料,所以需要確認item裡面有沒有內容,如果沒有的話 就回傳。
我們設定要查詢的公司為“台積電”,這邊可以自己替換。

from googleapiclient.discovery import build
# search_result = {}

query = "台積電"
def GoogleSearch(query):
  search_result = []
  SEARCH_API = "*****************************"
  SEARCH_ENGINE_ID = "**************"
  service = build("customsearch", "v1", developerKey=SEARCH_API, cache_discovery=False)
  res = service.cse().list(q=query, cx=SEARCH_ENGINE_ID).execute()
  # 處理搜尋結果:
  search_items = res.get('items')
  if search_items is None:
    return search_result
  for item in res['items']:
    try:
      title = item.get('title').replace("\n", "",20).replace("\xa0","",20)
      snippet = item.get('snippet').replace("\n", "",30).replace("\xa0","",30)
      search_result.append({"Title": title, "Content":snippet})
    except:
      continue
  return search_result
search_result = GoogleSearch(query)

https://ithelp.ithome.com.tw/upload/images/20240819/201683858U8MxOEvkF.jpg
雖然官方API很好,但因為不確定哪裡設定有問題,一直沒辦法準確篩選出想要的資料,雖然可以提取到Title和內文,但太多垃圾資料,所以後來我改用非官方API。

非官方 API

https://github.com/Iceloof/GoogleNews

安裝套件

你需要安裝 GoogleNews 套件。你可以使用以下命令來安裝:

!pip install GoogleNews

2. 設定相關參數

你可以使用以下程式碼來設定相關參數並獲取新聞數據:

from GoogleNews import GoogleNews

googlenews = GoogleNews(period='3d', lang='zh', region='TW')
googlenews.get_news('鴻海')
googlenews.get_texts()

https://ithelp.ithome.com.tw/upload/images/20240819/20168385iyQ15s4IqL.jpg

3. 獲取新聞標題和摘要

你還可以獲取新聞的標題和摘要,使用以下方法:

# 獲取新聞標題和摘要
news_results = googlenews.results()

# 打印新聞標題和摘要
for result in news_results:
    print(f"Title: {result['title']}")
    print(f"Snippet: {result['desc']}")

這樣就可以使用 Google News API 獲取最新的新聞數據,並根據你的需求進行處理和分析。
之後我們會需要這些資料進行股市分析

對於我這種不會看盤的人和追新聞的人應該用得到? 雖然不是很準確,但多少有點用處,不用自己爬文章。
另外近期中信金可以關注一下
[新聞] 中信金每股14.55元收購 新光金員工暴動了
https://www.ptt.cc/bbs/Stock/M.1724417494.A.7FA.html


上一篇
【AI筆記】30天從論文入門到 Pytorch 實戰:如何修改與優化模型 Day 21
下一篇
【AI筆記】30天從論文入門到 Pytorch 實戰:製作屬於自己的資料集 Day 23
系列文
【AI筆記】30天從論文入門到 Pytorch 實戰26
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言