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.textandr.json() - Extracted
totalCountto compute the total page count and collected in a loop with pagination - Received the same data in both
jsonandxmland compared them - Organized results into a
DataFrameand 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
datetimeandpd.date_rangeto 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.