쫑가 과정

4주차 - wsl에서 selenium 인스타 정보 엑셀수집하기 본문

프로그래밍 공부/파이선_정보취합하기

4주차 - wsl에서 selenium 인스타 정보 엑셀수집하기

쫑가 2021. 5. 28. 15:24

물건 정보 수집을 해봤으니 이제 트렌드 파악을 위한 인스타그램 정보를 수집해보자

작동 방법은 일반적으로 마우스와 키보드를 이용해 웹에서 접속하는 방식을 사용할 거다.

 

로그인화면 -> id,pw 입력 후 로그인 -> 원하는 #해시태그 검색 -> 검색 결과에서 원하는 정보 수집하기

 

준비물

wsl, virtualenv 가상 환경

beautifulsoup

pandas

selenium

driver

VcXsrv

lxml

Selenium

Selenium이 뭔지 본문으로 가서 보자

https://www.selenium.dev/documentation/en/introduction/the_selenium_project_and_tools/

 

The Selenium project and tools :: Documentation for Selenium

The Selenium project and tools Selenium controls web browsers Selenium is many things but at its core, it is a toolset for web browser automation that uses the best techniques available to remotely control browser instances and emulate a user’s interacti

www.selenium.dev

핵심은 브라우저 인스턴스를 원격으로 제어하고 브라우저와 사용자의 상호 작용을 모방하는 데 사용할 수 있는 최고의 기술을 사용하는 웹 브라우저 자동화를 위한 도구이다.

사용자는 사용자가 수행하는 일반적인 활동을 실행할 수 있습니다. 필드에 텍스트 입력, 드롭 다운 값 및 확인란 선택, 문서의 링크 클릭. 또한 마우스 이동, 임의의 JavaScript 실행 등과 같은 많은 컨트롤을 제공한다.

더보기

Selenium is many things but at its core, it is a toolset for web browser automation that uses the best techniques available to remotely control browser instances and emulate a user’s interaction with the browser.

It allows users to simulate common activities performed by end-users; entering text into fields, selecting drop-down values and checking boxes, and clicking links in documents. It also provides many other controls such as mouse movement, arbitrary JavaScript execution, and much more.

간단하게 말하면

사용자의 행동을 따라서 키보드 입력이나 마우스 이동, 클릭 등 을 할 수 있다는 말이다.

설치

※항상 설치는 가상 환경에서 진행한다.

설치는 어렵지 않다. 밑 링크로 들어가서 하라는 데로 하자.

https://pypi.org/project/selenium/

 

selenium

Python bindings for Selenium

pypi.org

잘 모르겠다면 그냥 따라 하자. 나는 아래처럼 입력했다.

pip3 install selenium

Drivers

Selenium은 선택한 브라우저와 인터페이스 하기 위한 드라이버가 필요합니다. 예를 들어 Firefox에는 geckodriver 가 필요하며 아래 예제를 실행하기 전에 설치해야 합니다

더보기

Selenium requires a driver to interface with the chosen browser. Firefox, for example, requires geckodriver, which needs to be installed before the below examples can be run.

selenium을 작동하기 위해서는 내가 사용하는 브라우저에 맞는 드라이버를 설치해야 한다.

Chrome: https://sites.google.com/a/chromium.org/chromedriver/downloads
Edge: https://developer.microsoft.com/en-us/microsoft-edge/tools/webdriver/
Firefox: https://github.com/mozilla/geckodriver/releases
Safari: https://webkit.org/blog/6900/webdriver-support-in-safari-10/

 

나는 Chrome을 사용하기에 chromedriver를 설치했다.

1 단계. chrome 설치

wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb

sudo apt install ./google-chrome-stable_current_amd64.deb

2 단계. chrome driver 설치

Chrome 설치, 버전 확인

google-chrome --version

예) Google Chrome 90.0.4430.212 

 

본인 chrome 버전에 맞춰서 설치한다.

 

설치 코드

sudo wget https://chromedriver.storage.googleapis.com/90.0.4430.24/chromedriver_linux64.zip
#https://chromedriver.storage.googleapis.com/90.0.4430.2 에서 chromedriver_linux64.zip 다운로드

unzip chromedriver_linux64.zip
#chromedriver_linux64.zip 알집풀기

설치 완료.

 

VcXsrv

왜 필요한가 알아야 할 필요가 있다.

WSL  : 간단하게 윈도우 10에서 네이티브로 리눅스 실행 파일(ELF)을 실행하기 위한 호환성 계층이다. (위키백과)(Microsoft)
(WSL 버전확인방법)
GUI  : 사용자가 편리하게 사용할 수 있도록 입출력 등의 기능을 알기 쉬운 아이콘 따위의 그래픽으로 나타낸 것이다. (위키백과
X Window System  주로 유닉스 계열 운영체제에서 사용되는 윈도 시스템 및 X 윈도우 GUI환경이다. 
디스플레이 장치에 을 표시하며 마우스와 키보드 등의 입력 장치의 상호작용 등을 관리해 GUI 환경의 구현을 위한 기본적인 프레임워크를 제공한다. (위키백과)
대표적으로 XmingVcXsrvX410 등

만화로 보기 (https://joone.net/2018/06/21/22-x-window-%ed%83%84%ec%83%9d/)

WSL은 문자 콘솔 위주의 명령어들이라서 X Window System 등 그래픽 서버를 설치해야 GUI 그래픽 어플리케이션을 지원한다.

프로그램이 GUI 창을 띄워달라고 X server에 요청“하면, “X server가 요청을 처리하여 GUI 창을 띄우는 것“ (https://evandde.github.io/wsl2-x/)

 

이 글에서는 VcXsrv을 사용하겠다.

설치

1 단계. 설치

https://sourceforge.net/projects/vcxsrv/

 

VcXsrv Windows X Server

Download VcXsrv Windows X Server for free. Windows X-server based on the xorg git sources (like xming or cygwin's xwin), but compiled with Visual C++ 2012 Express Edition. Source code can also be compiled with VS2008, VS2008 Express Edition and VS2010 Expr

sourceforge.net

 

2 단계. VcXsrv Windows X Server 설정

Multiple windows 선택

Display number 0

Start no client 선택

Clipboard

primary Selection

Native opengl 선택

 Additional parameters for VcXsrv에 -ac 작성

현재 설정을 계속 사용하기 위해 Save configuration을 클릭해서 파일을 저장합니다.

 

마침을 누르고 작업표시줄에 해당 아이콘이 있다면 완료!

 

3 단계. Linux 배포판 설정

 

terminal에서 아래 명령어를 입력하여 ~/.bashrc를 엽니다.

sudo nano ~/.bashrc

최하단에 아래 명령어를 추가하고 저장합니다.

export DISPLAY="`grep nameserver /etc/resolv.conf | sed 's/nameserver //'`:0"
export LIBGL_ALWAYS_INDIRECT=1

 

4 단계. 실행 테스트

gedit

완료!

 

오류가 많이 났었다. 

오류 해결을 위해 도움받은 사이트

더보기

https://stackoverflow.com/questions/43008622/python-linux-selenium-chrome-not-reachable

 

python linux selenium: chrome not reachable

I'm trying to run selenium on Ubuntu 16.10 Server, but I'm getting WebDriverException : Message : chrome not reachable (Driver info: chromedriver 2.9.248304, platform=Linux 4.8.0-22-generic x86_64)...

stackoverflow.com

https://github.com/microsoft/WSL/issues/4106

 

Can't use X-Server in WSL 2 · Issue #4106 · microsoft/WSL

Your Windows build number: (Type ver at a Windows Command Prompt) Microsoft Windows [Version 10.0.18917.1000] with Ubuntu 18.04, WSL 2. VcXsrv X Server Version 1.20.1.4 What you're doing and wh...

github.com

https://thenoface.tistory.com/5

 

WSL2에서 Ubuntu GUI 프로그램 실행하기 (VcXsrv)

WSL2가 Hyper-V를 이용한 VM 방식으로 바뀌면서 기존에 WSL1에서 사용하던 방식으로는 우분투의 GUI 프로그램을 실행할 수 없게 됐다. WSL1은 호스트와 이더넷을 공유했기에 WSL1와 (로컬호스트인) 127.0.0

thenoface.tistory.com

https://psychoria.tistory.com/739

 

Windows 10 WSL 2에서 리눅스 GUI 프로그램 실행하기

Windows 10 2004 업데이트에 WSL 2(Windows Subsystem for Linux 2)이 포함되었습니다. WSL 2를 설치하는 방법은 아래 링크에서 확인 가능합니다. 2020/07/07 - [Windows/Tip&Tech] - Windows 10 2004에서 WSL 2..

psychoria.tistory.com

https://league-cat.tistory.com/278

 

[Linux] chrome driver 에러 발생시 해결방법

selenium.common.exceptions.WebDriverException: Message: unknown error: Chrome failed to start: exited abnormally (unknown error: DevToolsActivePort file doesn't exist) (The process started from chro..

league-cat.tistory.com

 

lxml

https://lxml.de/index.html#introduction

 

lxml - Processing XML and HTML with Python

lxml is the most feature-rich and easy-to-use library for processing XML and HTML in the Python language. Introduction The lxml XML toolkit is a Pythonic binding for the C libraries libxml2 and libxslt. It is unique in that it combines the speed and XML fe

lxml.de

lxml XML 툴킷은 C 라이브러리 libxml2 및 libxslt에 대한 Pythonic 바인딩입니다. 이러한 라이브러리의 속도 및 XML 기능 완전성과 기본 Python API의 단순성을 결합한다는 점에서 독특합니다. 대부분 호환되지만 잘 알려진 ElementTree API 보다 우수합니다.

더보기

The lxml XML toolkit is a Pythonic binding for the C libraries libxml2 and libxslt. It is unique in that it combines the speed and XML feature completeness of these libraries with the simplicity of a native Python API, mostly compatible but superior to the well-known ElementTree API. 

뭔 말인지 모르겠다. 다시 검색!

 

lxml은 XML을 빠르고 유연하게 처리하는 파이썬 라이브러리입니다. XPath(XML Path Language)와 XSLT(Extensible Stylesheet Language Transformation)를 지원하며, 많이 쓰이는 ElementTree API를 구현합니다. 이 기사에서는 아주 큰 XML 자료를 처리할 때 lxml이 제공하는 사용 편의성과 성능에 초점을 맞춥니다. (한국데이터산업진흥원)


사용하는 이유

https://lxml.de/intro.html

 

Why lxml?

Aims The C libraries libxml2 and libxslt have huge benefits: Standards-compliant XML support. Support for (broken) HTML. Full-featured. Actively maintained by XML experts. fast. fast! FAST! These libraries already ship with Python bindings, but these Pytho

lxml.de

  • Standards-compliant XML support.
  • Support for (broken) HTML.
  • Full-featured.
  • Actively maintained by XML experts.
  • fast. fast! FAST!

표준 준수 XML 지원, (깨진) HTML 지원, 모든 기능을 갖춤, XML 전문가가 적극적으로 관리, 빠르고 빠르다!

 

설치.

https://lxml.de/installation.html#installation

 

Installing lxml

If your system does not provide binary packages or you want to install a newer version, the best way is to get the pip package management tool (or use a virtualenv) and run the following: If you are not using pip in a virtualenv and want to install lxml gl

lxml.de

pip install lxml

# 만약 virtualenv에서 pip를 사용하지 않고 
# 대신 lxml을 전역으로 설치하려면 아래 실행
sudo pip install lxml

끝.

 

코드 작성! 주석에 설명을 되어있으니 참고하세요 :)

from selenium import webdriver
import pandas as pd
from bs4 import BeautifulSoup
#정규식
import re
import time

# https://instagram.com/robots.txt
# robots.txt -> 크롤링 규약
# disallow / allow

# so chromedriver is assuming that chrome has crashed
chrome_options = webdriver.ChromeOptions()
# 밑의 옵션은 크롬을 안보고 진행하는 것
# chrome_options.add_argument('--headless')
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--disable-dev-shm-suage')
# 안전하지 않음 오류 제거
chrome_options.add_argument('ignore-certificate-errors')

# /c/program/python
# ./file : 현재경로
# ../file : 한칸 위로 올라감
# 설치되어있는 크롬 실행
driver = webdriver.Chrome("./chromedriver", options=chrome_options)

#인스타 접속
driver.get('https://www.instagram.com')
#접속로딩을 고려한 타임슬립 시간 설정
# 시간을 넉넉히 설정합니다.
# 유저가 들어갔을때 => 아이디 넣는 시간 비밀번호 넣는 시간.
time.sleep(5)

# 로그인에 필요한 사항을 브라우저 제어를통해 입력합니다.
email = 'your email' # 사용할 계정 정보 입력
# 로그인 창 선택
# loginForm > div > div:nth-child(1) > div > label >input'
input_id = driver.find_elements_by_css_selector(
   '#loginForm > div > div:nth-child(1) > div > label >input')[0]
# print(input_id)
# 혹시나 로그인창에 뭐가 적혀있을 수 도 있어서 아이디창 비우기
input_id.clear()
# id창에 email 넣어줌
input_id.send_keys(email)


password = 'your password' #비번 정보 수정
input_pw = driver.find_elements_by_css_selector(
    '#loginForm > div > div:nth-child(2) > div > label >input')[0]
input_pw.clear()
input_pw.send_keys(password)

# id와pw제출
input_pw.submit()
# 로그인 끝

time.sleep(3)
word = "고양이" # 검색할 해시태그, 띄어쓰기 사용하면 안됨
# 태그검색 url
# https://www.instagram.com/explore/tags/%EA%B3%A0%EC%96%91%EC%9D%B4/
# url encode 를 원하거나 한글로 보고싶은 경우에는
# https://meyerweb.com/eric/tools/dencoder/ 들어가서 encode/decode 하면됨

url = 'https://www.instagram.com/explore/tags/' + word
driver.get(url)
time.sleep(2)

#한 줄로 찾아봄
#row = driver.find_elements_by_css_selector("div.Nnq7c.weEfm")
#print(row)
#for r in row:
#    r.click()

# 첫게시물을 여는 함수를 정의합니다
def select_first(driver):
    first = driver.find_element_by_css_selector("div._9AhH0")
    first.click()
    time.sleep(5)

 # 내용을 가져오는 함수를 정의합니다.
def get_content(driver):
    html = driver.page_source
    # lxml이 기본적으로 bs4에서 제공해주는 것보다 속도가 빠름
    # pip install lxml
    soup = BeautifulSoup(html, 'lxml') # 내가 원하는데로 안가져오는 경우
    try:
        content = soup.select('div.C4VMK > span')[0].text
    except:
    # 에러가날경우에는 빈칸을 준다.
        content = ' '
    # 정규표현식을 활용하여 해시태그를 가져옵니다.
    tags = re.findall(r'#[^\s#,\\]+', content)
    # 작성일자를 가져옵니다.
    date = soup.select('time._1o9PC.Nzb55')[0]['datetime'][:10]
    # 좋아요 수를 가져옵니다.
    try:
        like = soup.select('div.Nm9Fw.zV_Nj > span')[0].text.replace(',', '')
    except:
        like = 0
    # 위치정보를 가져옵니다.
    try:
        place = soup.select('div.M30cS')[0].text
    except:
        place = ''
    # 수집한 정보를 리스트로 저장합니다.
    row = []
    # row.append(content)
    # row.append(date)
    data = [content, date, like, place, tags]
    return data

# 다음게시글을 여는 함수를 정의합니다.
def move_next(driver):
    right = driver.find_element_by_css_selector(
    'a.coreSpriteRightPaginationArrow')
    right.click()
    time.sleep(5)
# 함수를 차례대로 실행합니다.
# (5)개 게시물 보기
select_first(driver)
result = []
max_post = 5
for i in range(5):
    try:
        data = get_content(driver) 
        result.append(data)
        move_next(driver)
    except:
        time.sleep(2)
        move_next(driver)
#print(result[:1])

# 데이터프레임 만들고 엑셀로 저장하기
results_df = pd.DataFrame(result)
results_df.columns = ['content', 'data', 'like', 'place', 'tags']
results_df.to_excel('crawling_sample.xlsx', index=False)

 

+도움받은 사이트

더보기

https://evandde.github.io/wsl2-x/

 

WSL2에서 X window를 세팅하는 법

이 글에서는 WSL2를 설치한 뒤 X window(GUI)를 사용하기 위한 세팅 방법을 알아봅니다.

evandde.github.io

https://ubunlog.com/ko/vcxsrv-nos-permite-usar-apps-de-linux-con-interfaz-de-usuario-en-windows-10/

 

VcXsrv를 사용하면 Windows에서 GUI로 Linux 앱을 사용할 수 있습니다.

WSL을 사용하면 Windows에서 Linux 터미널을 사용할 수 있지만 GUI로 앱을 실행할 수는 없습니다. 후자가 원하는 경우 VcXsrv를 사용할 수 있습니다.

ubunlog.com

https://codefellows.github.io/setup-guide/windows/

 

Setting up WSL Version 2 and the Ubuntu app

Computer setup instructions for students starting classes at Code Fellows

codefellows.github.io

https://thenewth.com/2020/08/03/wslwindows-subsystem-for-linux-ubuntu-gui-%ED%99%98%EA%B2%BD-%EA%B5%AC%EC%84%B1/

 

WSL(Windows Subsystem for Linux) Ubuntu GUI 환경 구성

WSL에는 기본적으로 GUI 환경을 제공하지 않는다. 대부분의 경우 터미널로 출력되는 결과물만으로도 작업하는데 별다른 문제가 없지만 간혹 GUI가 꼭 필할 때도 있다. 리눅스의 GUI환경(X-window)은

thenewth.com

https://fossa.tistory.com/6

 

WSL2에서 GUI 프로그램 실행하기: 1편 XcXsrv 사용하기

VcXsrv Windows X Server 설치 화면을 표시할 수 있도록 해주는 소프트웨어 입니다. 공식 소스포지 페이지에서 다운로드가 가능합니다. 아래 링크에서 다운로드 받아서 설치합니다. ​ https://sourceforge.n

fossa.tistory.com

https://velog.io/@mgm-dev/%EB%94%94%EB%B2%84%EA%B9%85-WSL2%EC%97%90%EC%84%9C-Selenium-%EC%85%8B%ED%8C%85

 

WSL2에서 Selenium 셋팅

start testing

velog.io

 

 

Comments