반응형

예전 방식이라 잘되지 않는다. 

다른 url로 했을때 데이터는 잘 가져왔다. 

css 보안이 걸려있는듯. 

 

##  인스타그램 이미지 크롤링
#    
##
import os
import sys
import konlpy
import pandas as pd
import numpy as np
os.environ['JAVA_OPTS'] = 'Xmx4096M'
    
## 시간 표시  ##################################### 
import time
import datetime
now = datetime.datetime.now()

timeserise = time.time()
timeserise = str(int(timeserise))
print(timeserise)
print(now)
#################################################  


#작업하는 경로(위치)가 어디인지 확인
print(os.getcwd())

prePath = "./Project/instagram_cr/"
file_name = prePath + "outputfile0.txt" 

# 라이브러리 추가
from bs4 import BeautifulSoup  #불러온 데이터를 구분지어 원라는 데이터 출력
from selenium import webdriver #Chromedriver를 사용하여, 자동화 시스템 구동
## chrome 버전 안맞으면 아래와 같은 에러 발생함. chromedriver 버전 확인 필수
#  selenium.common.exceptions.SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 94
# Current browser version is 105.0.5195.102 with binary path C:\Program Files\Google\Chrome\Application\chrome.exe
# 
# GoUrl : https://chromedriver.storage.googleapis.com/index.html?path=105.0.5195.52/
##


from urllib.request import urlopen
from urllib.parse  import quote_plus # ASCII 형태로 자동 변형
import requests
import shutil
 


testurl_01 = "https://www.instagram.com/explore/tags/"
testurl_02 = input("Please input the word to search for : ")
testurl_03 = testurl_01 + quote_plus(testurl_02)


print(testurl_03)

## 아래 오류때문에 추가함. options
#  USB: usb_device_handle_win.cc:1048 Failed to read descriptor from node connection: 시스템에 부착된 장치가 작동하지 않습니다. 
## options start
options = webdriver.ChromeOptions()
options.add_experimental_option("excludeSwitches", ["enable-logging"])
#browser = webdriver.Chrome(options=options)
## options end 

#driver_01 = webdriver.Chrome()
driver_01 = webdriver.Chrome(options=options)
driver_01.get(testurl_03)

html_01 = driver_01.page_source
#print(html_01)

Source_01 = BeautifulSoup(html_01,"html.parser")
#Source_01 = BeautifulSoup(html_01,"lxml")
#Source_01 = BeautifulSoup(html_01)

time.sleep(5)

#print(Source_01)
print(Source_01.prettify())
 
o = open(prePath +'result_list.txt', 'w', encoding='utf-8')
o.write("")
o.write(Source_01.prettify())
o.close()    




var_list = [1, 3, 5, 7, 9]
for ii in var_list:
    print("----------------------------------------")


Demo_insta = Source_01.select('._a3wf._-kb.segoe') 
print(Demo_insta)

for each_div in Source_01.findAll('div',{'class':'list'}):
    print(each_div)


"""
x_1 = 1

for i in Demo_insta:
    print("https://www.instagram.com/" + i.a['href'])
    #img_01 = i.select_one('_aagt').img['src']
    #print(img_01)
"""

driver_01.close()
반응형
반응형
예제로 배우는 파이썬 - Selenium 사용하기 

1. Selenium 소개

Selenium은 웹 브라우져를 컨트롤하여 웹 UI 를 Automation 하는 도구 중의 하나이다. Selenium은 Selenium Server와 Selenium Client가 있는데, 로컬 컴퓨터의 웹 브라우져를 컨트롤하기 위해서는 Selenium Client 를 사용한다 (여기서는 Selenium 3 사용). Selenium Client는 WebDriver라는 공통 인터페이스(Common interface)와 각 브라우져 타입별(IE, Chrome, FireFox 등)로 하나씩 있는 Browser Driver로 구성되어 있다.

2. Selenium 설치

Selenium을 설치하기 위해서는 먼저 아래와 같이 pip 을 사용하여 Selenium Client 모듈을 설치한다.

pip install selenium

다음으로 사용할 브라우저별 Selenium 드라이버를 설치한다. 드라이버가 설치된 후, 해당 드라이버의 경로를 실행 PATH에 넣어 준다. 아래는 대표적인 브라우저별 설치 링크이다. 특별한 이유가 없다면 Selenium이 가장 잘 동작하는 Firefox를 사용하는 것이 좋다.

3. Selenium 사용법

Selenium을 사용하기 위해서는 먼저 selenium.webdriver 모듈을 import 한 후, webdriver.Firefox() 를 호출하여 브라우져를 실행시킨다. 만약 크롬을 사용할 경우 webdriver.Chrome()을 호출하고, Edge를 사용할 경우 webdriver.Edge()을 호출한다.

브라우져를 띄운 상태에서 특정 웹사이트로 이동하기 위해서는 아래와 같이 browser 객체의 get() 메서드를 사용한다.

1
2
3
4
5
6
from selenium import webdriver
 
browser = webdriver.Firefox()
# browser = webdriver.Chrome()
 
browser.get("http://python.org"

Selenium은 웹페이지 내의 특정 요소(들)을 찾는 많은 메서드들을 제공하고 있는데, 이들은 보통 한 요소를 리턴하는 find_element_*() 혹은 복수 요소를 리턴하는 find_elements_*() 메서드로 구분된다. 자주 사용되는 몇가지 검색 메서드를 예를 들면, 특정 태그 id 로 검색하는 find_element_by_id(), 특정 태그 name 속성으로 검색하는 find_element_by_name(), CSS 클래스명으로 검색하는 find_element_by_class_name(), CSS selector를 사용해 검색하는 find_element_by_css_selector() 등이 있는데, 예상되는 결과가 복수이면 find_element_* 대신 find_elements_* 를 사용한다.

검색 결과 리턴되는 객체는 FirefoxWebElement 와 같이 *WebElement 타입의 객체가 되는데, 리턴된 요소는 WebElement 타입 타입의 속성이나 메서드를 사용하여 데이타를 얻거나 특정 행위를 할 수 있다. 예를 들어, WebElement의 text는 요소 내의 문자열을 리턴하고, tag_name 은 해당 요소의 태크명 (예: a, span) 을 리턴하며, clear() 메서드를 호출하면 text 입력 영역을 초기화하고, click() 메서드를 호출하면 해당 요소를 클릭한다.

아래 예제는 python.org 웹사이트를 방문해서 상단 메인 메뉴 문자열을 출력하고, PyPI 메뉴를 클릭한 후 5초 후에 브라우저를 종료하는 예이다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
from selenium import webdriver
import time
 
browser = webdriver.Firefox()
browser.get("http://python.org")
 
menus = browser.find_elements_by_css_selector('#top ul.menu li')
 
pypi = None
for m in menus:
    if m.text == "PyPI":
        pypi = m
    print(m.text)
 
pypi.click()  # 클릭
 
time.sleep(5) # 5초 대기
browser.quit() # 브라우저 종료








...


반응형
반응형
http://code.google.com/p/selenium/

Overview  - http://docs.seleniumhq.org/

This is the site for developers of the Selenium browser automation framework. If you're developing with the framework, please go to Selenium HQ.

If you're a user of Selenium, and would like the latest documentation, please head over to Selenium HQ. If you'd like to report an issue, please click on the "Issues" tab above

If you're a user of WebDriver, and would like to file some bugs, then please also click on the "Issues" tab above. For documentation aimed at developers of the webdriver framework itself, please head over to the wiki.

The Selenium project hosts an implementation of the W3C WebDriver spec.

User Documentation

Related Projects

The following projects are related to Selenium and you may find it interesting:

Note the alternative language bindings are supported independently, and not by the selenium project.

Developer Documentation

Please consult the wiki or the project issue tracking for documentation relevant for working on the selenium framework itself. Suggested starting places for newbies are the BuildingWebDriver page, for instructions on how to build the software, the ArchitecturalOverview to understand how the pieces fit together, and perhaps the JsonWireProtocol for an insight into how the RemoteWebDriver works.

 

 

 

.

반응형

+ Recent posts