IT2022. 3. 31. 23:08
반응형

1. 태그의 클래스 값만 가져오는 함수.

 

태그의 지정된 클래스 값을 가져오는 함수를 만들어 보겠습니다.

from urllib.request import urlopen
from bs4 import BeautifulSoup

웹 크롤링을 위해 가장 기본이 되는 라이브러리를 불러오겠습니다. 간략하게 설명하면 urlopen은 url 페이지의 html 코드를 가져오는 라이브러리이고 BeautifulSoup는 html 문서를 파싱해 데이터를 쉽게 가져올 수 있도록 도와주는 라이브러리입니다.

def getClassValue(url, tag, className) :
    html = urlopen(url)
    bsObject = BeautifulSoup(html, "html.parser")
    content = bsObject.body.find(tag,{"class", className})
    return content.text  

getClassValue는 입력된 url을 urlopen으로 html 소스를 가져온 뒤 BeautifulSoup로 파싱 합니다. 파싱 된 데이터에서 입력된 tag와 className을 찾고 마지막에 해당 태그에 있는 value값을 리턴하는 함수입니다.

 

find를 쓰게 되면 1개 항목만 가져오게 됩니다. 혹시 모든 항목을 검색하고 싶다면 find_all로 변경하면 되고 배열로 값을 받을 수 있습니다.

 

2. 네이버 스토어 상품명 가져오기

 

url_list = [
    "https://smartstore.naver.com/soommask/products/4828127993",
    "https://smartstore.naver.com/aseado/products/4837257765",
    "https://smartstore.naver.com/aseado/products/4837266971",
    "https://smartstore.naver.com/aseado/products/3765693172",
    "https://smartstore.naver.com/aer-shop/products/4722827602",
    "https://smartstore.naver.com/aer-shop/products/4722827602",
    "https://smartstore.naver.com/korea-mask/products/4825762296",
    "https://m.smartstore.naver.com/ygfac/products/3905641271",
    "https://smartstore.naver.com/gonggami/products/4705579501"
];

상품명을 가져오기 위한 주소를 배열에 담아줍니다.

titles = []

tag = 'strong'
className = 'title_simplebuy'

for url in url_list :
    titles.append(getClassValue(url, tag, className))    

검색할 태그와 클리스 이름을 정의하고 for문으로 배열에 있는 데이터들을 실행하며 title을 수집합니다.

print(titles)

위와 같이 출력되는 것을 볼 수 있습니다.

 

3. 가격 가져오기

 

제목처럼 이제 가격을 가져오겠습니다.

위에선 이미 태그를 분석하여 상품명이 있는 태그와 클래스를 알았기 때문에 한 번에 가져올 수 있었습니다.

이번에는 어떤 태그에 가격이 있을지 확인하여 가져오는 방법을 정리하겠습니다.

html= urlopen("https://smartstore.naver.com/sangkong/products/4762917002")
bsObject = BeautifulSoup(html, "html.parser")
bsObject

BeautifulSoup로 파싱 한 데이터를 출력해 보면 위와 같이 확인할 수 있습니다.

이 요소들 중에 가격이 표시된 부분을 찾아봅시다.

<input name="productSalePrice" type="hidden" value="18000"/>

위 태그에 가격이 있는 것을 발견할 수 있네요

이제 위에서 했던 함수를 응용해서 값을 가져오는 함수를 만들어 보겠습니다.

def getNameValue(url, tag, name) :
    html = urlopen(url)
    bsObject = BeautifulSoup(html, "html.parser")
    content = bsObject.find(tag, {"name": name})
    return content.get('value')  

해당 태그의 value 값을 가져오도록 조금 수정했습니다.

이제 다시 함수를 돌려줄까요?

prices = []

tag1 = 'input'
name = 'productSalePrice'

for url in url_list :
    prices.append(getNameValue(url, tag1, name))
print(prices)

상품마다 가격을 가져오는 것을 확인할 수 있습니다.

반응형
Posted by Dream Come True
IT/인터넷 마케팅2019. 12. 16. 13:38
반응형

아래소스를 사용하면 pyautogui 마우스 좌표를 쉽게 표시 할 수 있습니다.

Here is a short Python 3 : python3 버젼
#! python3
import pyautogui, sys
print('Press Ctrl-C to quit.')
try:
    while True:
        x, y = pyautogui.position()
        positionStr = 'X: ' + str(x).rjust(4) + ' Y: ' + str(y).rjust(4)
        print(positionStr, end='')
        print('\b' * len(positionStr), end='', flush=True)
except KeyboardInterrupt:
    print('\n')

 

 

 


Here is the Python 2 version: python2 버젼


#! python
import pyautogui, sys
print('Press Ctrl-C to quit.')
try:
    while True:
        x, y = pyautogui.position()
        positionStr = 'X: ' + str(x).rjust(4) + ' Y: ' + str(y).rjust(4)
        print positionStr,
        print '\b' * (len(positionStr) + 2),
        sys.stdout.flush()
except KeyboardInterrupt:
    print '\n'

 

 

결과는 다음과 같이 실시간으로 표시 된다.

>>> pyautogui.size()
(1920, 1080)
>>> pyautogui.position()
(187, 567)

 

반응형

'IT > 인터넷 마케팅' 카테고리의 다른 글

python 엑셀 자동화 [업무자동화]  (13) 2021.02.24
defold 한글 메뉴얼  (4) 2020.12.17
python 특정 디렉토리 파일 이동 프로그램  (7) 2012.01.10
python Function Description  (4) 2010.12.07
log 파일 생성 raw input  (6) 2010.12.07
Posted by Dream Come True
카테고리 없음2019. 12. 9. 00:01
반응형

순서는 없습니다.

알아서들 필요한것만 찾으시면 됩니다.

 

 

1. 웹캠 얼굴 인식 OpenCV 를 사용한 것 이것은 공장에서 수도 없이 송장을 만들 것이다 만약 그것들을 사진으로 다시 저장하고 문서화 하기 위해서는 OpenCv 가 가장 좋은 대안 일것이다.

 

송장을 스캔을 하든 사진을 찍든 해서 특정 폴더에 넣어주면 폴더의 이미지 파일을 모두 텍스트로 변환 한다 든지

하는 곳에 응용 할 수있다.

 

import cv2

#웹캠에서 영상을 읽어온다
cap = cv2.VideoCapture(0)
cap.set(3, 640) #WIDTH
cap.set(4, 480) #HEIGHT

#얼굴 인식 캐스케이드 파일 읽는다
face_cascade = cv2.CascadeClassifier('haarcascade_frontface.xml')

while(True):
    # frame 별로 capture 한다
    ret, frame = cap.read()

    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray, 1.3, 5)

    #인식된 얼굴 갯수를 출력
    print(len(faces))

    # 인식된 얼굴에 사각형을 출력한다
    for (x,y,w,h) in faces:
         cv2.rectangle(frame,(x,y),(x+w,y+h),(255,0,0),2)

    #화면에 출력한다
    cv2.imshow('frame',frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()

 

 

 

2. Selenium : 웹 자동화 구글의 크롭의 자동화를 활용해 웹상에서 로그인 및 자료 추출 주료 입력 자료를 추출하여

엑셀에 넣거나 텍스파일 형식으로 저장할때 사용 할 수 있다. 조금더 노력 하면 DB에 인서트 하는것도 할 수 있다.

from selenium import webdriver
path = "chromedriver.exe"
driver = webdriver.Chrome(path)
driver.get("http://google.com/")
search_box = driver.find_element_by_name("q")
search_box.send_keys("셀레니엄")
search_box.submit()

 

 

2. pyautogui GUI(Graphic User Interface) 상에서 키보드와 마우스를 자동화 할 수 있다. 이것은 메크로 기능으로 여러 가지 작업을 자동화 할 수 있다. 아래 예제는 Google 의 Admob 광고의 승인을 자동 클릭 해서 승인 해주는 메크로다.

현재는 기능 구현만 했지만 위에 것과 같이 사용 하면 크롬을 실행 후 페이지 접속 과 로그인 까지 자동화 시켜

모든 작업을 자동화로 구현 가능하다.

import time
import pyautogui

x = int(100)

width, height = pyautogui.size()
current_mouse = pyautogui.position()
print(current_mouse)

print('width={0}, height={1}'.format(width, height))


# pyautogui.moveTo(2878, 998, duration=0.5)
pyautogui.press('end')

pyautogui.click( 1080, 919, duration=0.25)
pyautogui.press('end')
pyautogui.click(1100, 909, duration=0.25)

pyautogui.press('end')
pyautogui.click(1551, 920, duration=0.25)



def work():
    global x
    time.sleep(5)
    pyautogui.press('end')
    pyautogui.click(1551, 920, duration=0.25)
    x = x - 1
try:    
    while x > 0:
        work()
    else:
        pass

except KeyboardInterrupt:
    pass

현재 모든 분야에서 자동화에 대한 필요성이 나타나고 있다. 이것은 업무 혁신을 위해서는 피할 수 없는 시대의 한 흐름이다. 그업무의 자동화 중심에 python 이 있다 지금 까지는 엑셀을 잘하는 사람이 그나마 인정 받고 했을지 모르지만.

앞으로는 엑셀과 더불어 모든것을 자동화로 만들 수 있는 사람이 인정 받을 것이라 생각한다.

 

이곳에 관련 정보들을 이제부터 조금씩 찾아 모아 두겠다.

필요하신 분들은 참조 하시라.

그럼이만.

 

 

반응형
Posted by Dream Come True
IT/인터넷 마케팅2012. 1. 10. 09:51
반응형

특정 디렉토리의 파일들을 특정 디렉토리 로 날짜별 폴더를 만들어 그날짜에 맞는 파일을 폴더로 이동 시키는 것이다.
그림파일이나 로그파일 분석시 좋습니다.


http://jof4002.net/%EB%83%A5%EB%82%A0/Python 

냥날이라는 분의 코드를 모디 파이 했습니다.
참고하세요.


반응형

'IT > 인터넷 마케팅' 카테고리의 다른 글

python 엑셀 자동화 [업무자동화]  (13) 2021.02.24
defold 한글 메뉴얼  (4) 2020.12.17
python 마우스 실시간 위치 좌표로 표시  (6) 2019.12.16
python Function Description  (4) 2010.12.07
log 파일 생성 raw input  (6) 2010.12.07
Posted by Dream Come True