2023.12.27.
WebCrawling
Selenium(2)
셀레니움에서는 여러 페이지를 접속할 때 바로바로 인터넷 상에서 정보가 오가지 않을 때가 많다.
이 때문에 다음을 활용해서 시간을 지연시킬 수 있다.
1) time 패키지
- 무조건 일정 시간을 기다린다. 단점은 데이터가 중간에 들어와도 대기한다.
- 특정 시간 이상 재접속을 요청하는 경우 유용하다
2) implicit wait
- 최대 N초 기다리다가 정보가 오면 다음으로 넘어간다. 단, 정보가 일부분만 들어온 경우가 있을 수 있다.
- driver.implicit_wait(10)
3) explicit wait
- 내가 원하는 상태가 될 때까지 대기하는 방식이다. 여러가지 조건을 세팅해야한다.
- WebDriverWait(driver,5).untl()
실습3: 다나와 사이트
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
import time # --> 웹브라우저에 대해서 충분한 시간을 대기
# 요청하고 정보가 올 때 까지 기다리는 기능!!!!!
from selenium.webdriver.support.ui import WebDriverWait
# 상태
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support import expected_conditions as ec
from selenium.webdriver.common.keys import Keys
# 중간 이후부터는 bs4로 추출할 예정
from bs4 import BeautifulSoup
#내 드라이브
path = r'C:크롬드라이버 위치'
# 셀레니움을 통한 웹브라우저 세팅
s = Service(path)
driver = webdriver.Chrome(service=s)
# 기본적으로 접근할 url
base_url = "https://prod.danawa.com/list/?cate=112758&15main_11_02="
driver.get(base_url)
# 지급 상태에서는 제조사에 대한 조건이 다 안보이므로
# 제조사에 대한 확장 버튼을 찾아서 - 클릭
btn_path = '//*[@id="dlMaker_simple"]/dd/div[2]/button[1]'
# 앞에 한 대로 대가를 한 번 해보겠다.
WebDriverWait(driver,5).until(ec.presence_of_element_located((By.XPATH, btn_path))).click()
# 애플 제조사 버튼이 나타났으니 그 버튼을 찾아 클릭
apple_btn = '//*[@id="searchMaker1452"]'
driver.find_element(By.XPATH, apple_btn).click()
time.sleep(3) #-> driver에 충분하게 apple 정보가 안들어온다
# beautifulSoup을 이용해보자
soup = BeautifulSoup(driver.page_source, 'html.parser')
temp = soup.find("div", class_="main_prodlist main_prodlist_list").find_all("li", class_="prod_item prod_layer")
for i_data in temp:
# --> i_data에서 제품명만 출력해보자!!!
print(i_data.find("a", {"name":"productName"}).text.strip())
print("-"*100)
추가) Curl Api
외국, 게임사 api쪽에서 주로 많이 볼 수 있다.
API 요청하는 경우 curl만 나오는 사이트가 있는데, 아래 사이트에 접속해서 curl command를 붙여넣기 하고 각 원하는 언어로 변경이 가능하다.
Convert curl commands to code
Privacy We do not transmit or record the curl commands you enter or what they're converted to. This is a static website (hosted on GitHub Pages) and the conversion happens entirely in your browser using JavaScript. There is also a VS Code extension and a c
curlconverter.com
Pandas
여러 개의 DataFrame을 하나로 합치는 방법
1. Concat
그냥 단순하게 옆 또는 아래로 이어 붙이는 방식
axis = 0(옆으로 붙이기)
axis = 1(아래로 붙이기)
pd.concat( [ 합칠대상1, 합칠대상2, 합칠대상3,,,], axis=0/1, ignore_index=T/F)
2) Join(Merge)
sql의 join을 사용해 특정 조건에 맞는 경우들에 한해 합친다.
Pandas에서는 이 역할을 Merge를 통해 활용한다.
pd.merge(L-DF, R-DF, how="~~~", on="기준되는 공통 컬럼명")
3) 예제
아래 데이터를 연결해보자
baseball_player = pd.DataFrame(
{
"player_name":["권혁","이범호","필","박병호","양준혁"],
"team_no" : [1993, 2001, 2001, 2010, None]
}
)
baseball_player
baseball_team = pd.DataFrame(
{
"team_name" : ["한화","두산","기아","넥센"],
"team_home" : ["대전","서울","광주","고척"],
"team_id" : [1993, 1999,2001, 2010]
}
)
baseball_team
SQL을 활용한다면 아래와 같이 공통 컬럼을 기준으로 join 할 것이다.
# SQL --> left join
select * from A left join B on A.id = B.id; # 1: n
Merge를 활용한다면 아래와 같이 데이터를 연결할 것이다.
pd.merge(baseball_player, baseball_team,
how='left',
left_on = 'team_no',
right_on = 'team_id')
연결 방식에 따라 how에는 'left', 'right', 'inner', 'outer'등을 활용할 수 있다.
'ASAC 빅데이터전문가과정 > Python' 카테고리의 다른 글
ASAC 23일차 _ 데이터 핸들링(1) (0) | 2024.08.12 |
---|---|
ASAC 22일차 _ Matplotlib (0) | 2024.08.08 |
ASAC 19일차 _ WebCrawling(3) : 웹사이트(2), Selenium(1) (0) | 2024.08.01 |
ASAC 18일차 _ WebCrawling(2) : JSON(2), XML, 웹사이트(1) (0) | 2024.08.01 |
ASAC 17일차 _ 파이썬(Python) Numpy/Pandas 4일차, WebCrawling(1) : Json(1) (6) | 2024.07.24 |