Programming/Python
[python] requests와 BeautifulSoup을 이용해 웹페이지 정보 가져오기
woonizzooni
2019. 6. 14. 01:32
아주(!!) 초단간 코드로...
- 정보 선택 : 아래 그림의 '다음을 시작페이지로'를 가져와보자 (https://www.daum.net)
- 코드 작성 (예외처리 등은 고려하지 않음. 말그대로 예제...)
#!/usr/bin/python
# -*- coding: utf-8 -*-
import requests
from bs4 import BeautifulSoup
def get(url):
headers = {\
'Host':'www.daum.net',\
'Connection':'close',\
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)',\
'Accept':'*/*',\
'Accept-Encoding':'gzip, deflate',\
'Accept-Language':'ko-KR,ko;q=0.9,en-US;q=0.8,en;q=0.7',\
'Cache-Control':'max-age=0'\
}
res = requests.get(url, headers=headers, allow_redirects=True)
if res.status_code == 200:
dom = BeautifulSoup(res.content, 'html.parser')
homepage = dom.findAll('a', {'id':'homePage'})[0].string
print(homepage)
else:
print("Error! [%d : %s]" % (res.status_code, res.request_url))
url = 'https://www.daum.net'
get(url)
- 실행결과
> python get.py
다음을 시작페이지로