Series Data Voyage Training Log

~1 min read

First Data Collection: Public APIs and Crawling

Collecting chicken-shop data from a public commercial-district API, crawling Hana Bank exchange rates with read_html and automating it, then Selenium and a DB, as a first experience of the 'fetch and store' pipeline.

TrainingScrapingAPI

Fetching Data from an API

The first target was the Small Enterprise commercial-district (sangkwon) information API. I started by reading the operation spec in the guide and assembling requests with requests.get(url, params=payload).

url = "http://apis.data.go.kr/B553077/api/open/sdsc2/storeListInUpjong"
payload = dict(divId="indsSclsCd", key="I21006",  # subcategory code (chicken)
               numOfRows=100, pageNo=1, type="json",
               serviceKey=os.getenv("service_key"))
r = requests.get(url, params=payload)

The key learning points were these.

  • Checked that status code 200 means OK and saw the difference between r.text and r.json()
  • Extracted totalCount to compute the total page count and collected in a loop with pagination
  • Received the same data in both json and xml and compared them
  • Organized results into a DataFrame and saved as CSV
  • Throttled API calls with time.sleep() to ease server load

Automating Exchange-Rate Collection via Crawling

Data without an API, you scrape directly. I read Hana Bank's exchange-rate page with pd.read_html. I hit an OSError here and learned to wrap HTML text in StringIO to treat it like a file.

  • Generated dates with datetime and pd.date_range to collect many days in a loop. This is the scheduler idea
  • Cleaned up the collected DataFrame's column names via .columns / .values
  • Saved the final result to a DB

Selenium and DB Setup

For pages that static requests couldn't handle, I drove a real browser with Selenium. I loaded the collected data into MySQL with SQLAlchemy and pymysql. This completed my first automated pipeline of crawling, cleaning, and storing.

Takeaway

Key point

I learned there are layers to "where and how do we get data." An API is cleanest. Without one, I do static crawling, and when that's blocked, browser automation. Collected data only becomes reusable once it's stored in a DB.