Selenium은 웹 어플리케이션 테스트를 위한 포터블 프레임 워크이다.
Requests는 비교적 호출이 쉽지만, 안되는 경우가 많다.
반면, Selenium은 사람이 화면에서 작동하듯이 쓸 수 있으며 비교적 어렵지만 Requests가 못하는 동작들을 호출할 수 있다.
from selenium import webdriver
import chromedriver_autoinstaller
import time
chromedriver_autoinstaller.install()
driver = webdriver.Chrome()
def input_element(xpath, key):
input_ = driver.find_element(By.XPATH, xpath).send_keys(key)
time.sleep(5)
def click_element(xpath):
driver.find_element(By.XPATH, xpath).click()
def login(id, pw):
id_xpath = '//*[@id="loginForm"]/div/div[1]/div/label/input' #single quote 사용
pw_xpath = '//*[@id="loginForm"]/div/div[2]/div/label/input'
click_xpath = '//*[@id="loginForm"]/div/div[3]/button/div'
input_element(id_xpath, id)
input_element(pw_xpath, pw)
click_element(click_xpath)
url = "https://www.instagram.com/"
driver.get(url)
login(id,pw)
hashtag = input()
url = f"https://www.instagram.com/explore/tags/{hashtag}/"
driver.get(url = url)
scroll_url = "https://www.instagram.com/nailedit_mj/"
driver.get(url = scroll_url)
time.sleep(6)
3번과 4번 과정을 함수화하면 다음과 같이 쓸 수 있다.
인자로 hashtag와 scroll_times를 받아서 해당 hashtag를 검색 후 스크롤을 지정한 만큼 동작하도록 한다.
hashtag, scroll_times = map(input().split())
def search(hashtag, scroll_times):
url = f"https://www.instagram.com/explore/tags/{hashtag}/"
driver.get(url = url)
time.sleep(6)
for _ in range(scroll_times):
driver.execute_script("window.scrollTo(0,document.body.scrollHeight);")
time.sleep(6)
1) 게시물 클릭하기
def click_post(number):
row = (number - 1) // 3 + 1
col = (number - 1) % 3 + 1
xpath = f'/html/body/div[2]/div/div/div[2]/div/div/div/div[1]/div[1]/div[2]/section/main/article/div/div/div/div[{row}]/div[{col}]'
click_element(xpath)
2) 좋아요 누르기
def like():
xpath = '/html/body/div[7]/div[1]/div/div[3]/div/div/div/div/div[2]/div/article/div/div[3]/div/div/section[1]/span[1]/div/div/span'
click_element(xpath)
3) 예시
아래 코드는 네번째 게시글 클릭 후 ❤️ 를 누르는 코드이다.
click_post(4)
like()
comment = input()
def put_comment(comment):
xpath = '/html/body/div[7]/div[1]/div/div[3]/div/div/div/div/div[2]/div/article/div/div[3]/div/div/section[1]/span[2]/div/div'
click_element(xpath)
comment_path = '/html/body/div[7]/div[1]/div/div[3]/div/div/div/div/div[2]/div/article/div/div[3]/div/div/section[3]/div/form/div/textarea'
click_element(comment_path)
input_element(comment_path, comment)
submit_path = '/html/body/div[7]/div[1]/div/div[3]/div/div/div/div/div[2]/div/article/div/div[3]/div/div/section[3]/div/form/div/div[2]'
click_element(submit_path)
put_comment(comment)