1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[Python]FastAPIを用いたWebスクレイピングAPI 作成方法 メモ

Posted at
  • FastAPIを用いたWebスクレイピング用APIの作成方法についてメモする。
  • 指定したキーワードでGoogle検索を行うAPIを作成する。
    • スクレイピング処理用のライブラリはrequestsとBeautifulSoupを利用する。

構成

fastapi_scraping --- scraper.py
				  |_ main.py

コード

  • scraper.py(スクレイピング部分)

import requests
import bs4

class Scraper():
def google_search(self, search_keyword):
# 指定したキーワードで検索
search_url = 'https://www.google.co.jp/search?q='+search_keyword
search_response = requests.get(search_url)

    # 検索結果をパース
    soup = bs4.BeautifulSoup(search_response.text, 'lxml')
    parsed_page = soup.select('div.kCrYT>a')

    # タイトル、URLの抽出
    items = []
    rank = 1
    for site in parsed_page:
        item = {
            'rank': rank,
            'title': site.select('h3.zBAuLc')[0].text,
            'url': site.get('href').split(
                '&sa=U&')[0].replace('/url?q=', '')
        }
        rank += 1
        items.append(item)
    return items

* `main.py`

```python
from fastapi import FastAPI
from scraper import Scraper
app = FastAPI()
scraper = Scraper()

@app.get("/{word}")
async def search_google(word):
    return scraper.google_search(word)

動作確認

  • 起動

    uvicorn main:app --reload
    INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
    INFO:     Started reloader process [2020] using statreload
    INFO:     Started server process [3816]
    INFO:     Waiting for application startup.
    INFO:     Application startup complete.
    
  • Swagger UIにアクセス

    http://localhost:8000/docs
    

    fastapi_swagger_ui.png

  • 「Get /{word}」を開く→「Try it out」を押下→「word」に検索ワードを入力→「execute」押下

    fastapi_swagger_ui_result.png

参考情報

1
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?