카테고리 없음
python 크롤링 request, bs4, BeautifulSoup 사용 (콘솔창 출력)
Canyi
2022. 10. 6. 17:05
pip3 install requests (나는 이미 설치가 되어있다.)
pip3 install bs4
pip3 install BeautifulSoup
에러를 확인하면 python3에서 아주 오래된 BeautifulSoup 릴리스를 사용하고 있어서 BeautifulSoup 4를 설치하라...
pip3 install BeautifulSoup4
pip3을 쓰는 이유도 나는 python 3버전을 사용하고 있기 때문이다. 그래서 pip 기능이 잘 안될 경우 업그레이드를 하거나 pip버전이름 추가해서 사용한다.
import requests
from bs4 import BeautifulSoup as bs # BeautifulSoup를 bs로 쓰겠다.
page = requests.get('https://library.gabia.com/')
soup = bs(page.text,"html.parser") #데이터 구조화
elements = soup.select('div.esg-entry-content')
for index, element in enumerate(elements,1): #index: data의 index를 1부터 시작
print(index,element.text)
반복문에서 출력할때 .format을 사용해서 데이터를 더 깔끔하게 보고싶을 때
import requests
from bs4 import BeautifulSoup as bs # BeautifulSoup를 bs로 쓰겠다.
page = requests.get('https://library.gabia.com/')
soup = bs(page.text,"html.parser") #데이터 구조화
elements = soup.select('div.esg-entry-content a > span') # a > span index와 content 정렬?
for index, element in enumerate(elements,1): #index: data 개수
print("{}번째 게시글 제목 : {}".format(index,element.text)) #format에 있는 데이터가 {}안에 각각 입력해서 출력
elements = soup.select('div.esg-entry-content') 에 a > span을 추가하고
print기능에 "{}".format 기능을 사용해 index와 element.text를 {}에 넣어서 예쁘게 출력
해당 글의 링크를 타서 기사를 보고 싶다?
elements = soup.select('div.esg-entry-content a.eg-grant-element-0')
elements = soup.select('div.esg-entry-content') 를 elements = soup.select('div.esg-entry-content a.eg-grant-element-0') 로 수정
print("{}번째 게시글: {}, {}".format(index,element.text,element.attrs['href']))
{} 를 추가하고 element.attrs['href'] 라는 기능을 추가하면 된다.
import requests
from bs4 import BeautifulSoup as bs # BeautifulSoup를 bs로 쓰겠다.
page = requests.get('https://library.gabia.com/')
soup = bs(page.text,"html.parser") #데이터 구조화
elements = soup.select('div.esg-entry-content a.eg-grant-element-0')
for index, element in enumerate(elements,1): #index: data 개수
print("{}번째 게시글: {}, {}".format(index,element.text,element.attrs['href']))