์์ธ์ฝ๋
import requests
from bs4 import BeautifulSoup
def get_exchange_rate(target1, target2):
headers = {
'User-Agent' : 'Mozilla/5.0',
'Content-Type' : 'text/html; charset=utf-8'
}
response = requests.get("https://kr.investing.com/currencies/{}-{}".format(target1, target2), headers = headers)
content = BeautifulSoup(response.content, 'html/parser')
containers = content.find('span', {'data-test':'instrument-price-last'})
print(containers.text)
get_exchange_rate('usd','krw')
์ค์๊ฐ ํ์จ ์ ๋ณด ํฌ๋กค๋ง ์ฝ๋๋ฅผ ๋ง๋๋๋ฐ, ํ์จ๋น๋ฅผ ๊ฐ์ ธ์ค๋ ํจ์๋ฅผ ๋ง๋ค์๋ค.
ํค๋๋ฅผ ์ถ๊ฐํ์ฌ ๋ก๋ด์ด ์ ์ํ ๊ฒ์ด ์๋ ์ฌ๋์ด ์ ์ํ ๊ฒ ์ฒ๋ผ ํ์๋ค.
๊ทธ๋ฆฌ๊ณ ์ผ๋ฐ์ ์ธ ๋ธ๋ผ์ฐ์ ๋ฅผ ์ด์ฉํ์ฌ ์ ์ํ ๊ฒ์ฒ๋ผ ๋ณด์ด๊ฒ ํ์๋ค.
requess ๋ผ์ด๋ธ๋ฌ๋ฆฌ๋ฅผ ์ด์ฉํ์ฌ ์ธ๋ฒ ์คํ ๋ท์ปด์ ์ ์ํ์ฌ ์์ฒญํ ์๋ต๊ฐ์ ๊ฐ์ง๊ณ ์ค๋ ค ํ์๊ณ , usd ์ ๋ํ krw ๊ฐ์ ๊ตฌํ๋ ค ํ๋ค.
Beautiful ๋ผ์ด๋ธ๋ฌ๋ฆฌ๋ฅผ ์ด์ฉํ์ฌ html๋ก ๊ฐ์ ๊ฐ์ ธ์์, ๋ฐ์ดํฐ๋ฅผ ์ฐพ๊ธฐ ์ข๊ฒ ํ๋ คํ๋ค.
๊ทธ๋ฆฌ๊ณ data-test ๋ฅผ instrument-price-last๋ฅผ ํตํด ์ต์ ๊ฐ(๋ง์ง๋ง ํ์จ ๋ฐ์ดํฐ)๋ฅผ ์ฐพ์๋ค.
๊ทธ๋ฆฌ๊ณ ํฌ๋กค๋ง์ ์งํํ์ฌ ์ถ๋ ฅํ๋ ค ํ์๋๋ฐ...
์๋ฌ์ฝ๋
---> 12 content = BeautifulSoup(response.content, 'html/parser')
13 containers = content.find('span', {'data-test':'instrument-price-last'})
14 print(containers.text)
c:\Users\bbeee\anaconda3\envs\py37\lib\site-packages\bs4\__init__.py in __init__(self, markup, features, builder, parse_only, from_encoding, exclude_encodings, element_classes, **kwargs)
249 "Couldn't find a tree builder with the features you "
250 "requested: %s. Do you need to install a parser library?"
--> 251 % ",".join(features))
252
253 # At this point either we have a TreeBuilder instance in
FeatureNotFound: Couldn't find a tree builder with the features you requested: html/parser. Do you need to install a parser library?
BeautifulSoup๋ฅผ ์ด์ฉํ์ฌ, ๋ณดํต HTML๊ณผ XML ํ์ผ์์ ๋ฐ์ดํฐ๋ฅผ ์ฝ์ด๋ผ ์ ์์ผ๋ฉฐ,
ํ์ด์ฌ ๋ผ์ด๋ธ๋ฌ๋ฆฌ๋ก์
ํธ๋ฆฌ๋ฅผ ํ์, ๊ฒ์, ์์ ํ๋๋ฐ ๊ฐํธํ๊ณ ์ฌ์ฉ์๊ฐ ๋ง๋ ํ์์ ํจ๊ป ์ฌ์ฉํ๋ค.
ํ์ง๋ง ์ฌ๊ธฐ์ html/parser ์ lxml ๋ฅผ ์ฌ์ฉํ๋๋ฐ, ํ์๋ html/parser๋ฅผ ์ฌ์ฉํด์ ํ์ฑ์ ์งํํ๋ คํ๋ค.
BeautifulSoup ๊ฐ์ฒด๋ฅผ ์์ฑํ์ฌ ๊ฐ์ฒด๋ฅผ ๋ง๋๋ ๊ณผ์ ์์ ํด๋น ์ค์ ๋ณด๋,
์ด๋ฐ ์ค๋ฅ๊ฐ ๋ด์ผ๋ฉฐ,
์๊ณ ๋ณด๋ / ๊ฐ ์๋ . ์ ์ฌ์ฉํด์ผํ๋ค.
ํด๊ฒฐ์ฝ๋
content = BeautifulSoup(response.content, 'html.parser')