PYTHON

파이썬 강좌 – 김플 스튜디오

 

  1. 파이썬 크롤링 예제 네이버 이미지 검색결과 한번에 다운로드 프로그램
  2. 파이썬 selenium 셀레니움 새탭 열고 닫는 방법
  3. 파이썬 반복문에서 사용하고 있는 리스트를 반복 중간에 변경하면 어떻게 될까요?
  4. vscode 사용법, 단축키 / 비주얼 스튜디오 코드
  5. 파이썬 인스타그램 크롤링 이미지 다운로드 beautifulsoup selenium 사용법
  6. 파이썬 자동화 selenium 사용법 브라우저 매크로 프로그램 만들기
  7. 파이썬 자동화 셀레니움(selenium) webdriver와 actionchains으로 웹사이트 매크로 제작
  8. 파이썬 selenium 셀레니움 팝업창 닫는 방법
  9. 파이썬 여러페이지 크롤링 네이버 블로그 검색결과 웹스크래핑
  10. 파이썬 크롤링 csv 파일저장 방법 네이버 모바일 검색결과 웹스크래핑
  11. 파이썬 강의 텍스트 파일 open 읽기 쓰기 추가하기 w, r, a 모드(with 포함)

 

 


 

파이썬 크롤링 예제 네이버 이미지 검색결과 한번에 다운로드 프로그램

 

from urllib.request import urlopen
from urllib.parse import quote_plus
from bs4 import BeautifulSoup

baseUrl = 'https://search.naver.com/search.naver?sm=tab_hty.top&where=image&query='
plusUrl = input('검색어를 입력하세요.')
url = baseUrl + quote_plus(plusUrl)

html = urlopen(url).read()
soup = BeautifulSoup(html, 'html.parser')
img = soup.find_all(class_='_img')

n = 1
for i in img:
    imgUrl = i['data-source']
    with urlopen(imgUrl) as f:
        with open('./img/' + plusUrl + str(n) + '.jpg', 'wb') as h:
            img = f.read()
            h.write(img)
    n += 1
    print(imgUrl)

print('다운로드 완료')

 

 


 

파이썬 selenium 셀레니움 새탭 열고 닫는 방법

 

# 파이썬 selenium 셀레니움 새탭 열고 닫는 방법
https://www.youtube.com/watch?v=36mSjaEH-hw

 

from selenium import webdriver
import time

driver = webdriver.Chrome()

driver.get('https://google.com')
time.sleep(1)

driver.execute_script('window.open("https://naver.com");')
time.sleep(1)

driver.switch_to_window(driver.window_handles[0])
time.sleep(1)

driver.close()

print(driver.window_handles)

 

 


 

3. 파이썬 반복문에서 사용하고 있는 리스트를 반복 중간에 변경하면 어떻게 될까요?

 

https://www.youtube.com/watch?v=2BXhwvnhnfQ

 

num = [1, 2, 3]

for i in num:
    print(i)
    num.append(i + 1)

# 무한 반복
# append 한다면 num 의 주소에 계속 추가해 나간다.

 

 

num = [1, 2, 3]

for i in num:
    print(i)
    num = [4, 5, 6]
print(num)

# [4, 5, 6] 
# num 에 [4, 5, 6] 을 할당해서 num 의 주소는 바꼈다.
# for 의 조건에 있는 num 은 기존 주소로 반복한다.
# id 키웓로 변수의 주소를 확인해 볼 것

 

 


 

4. vscode 사용법, 단축키 / 비주얼 스튜디오 코드

 

ctrl + shift + k : 행 삭제
alt + down/up : 행을 아래/위로 이동
ctrl + enter : 아랫 줄에 행 삽입
ctrl + shift + enter : 윗 줄에 행 삽입
ctrl + alt + down/up : 커서를 아래/위로 추가
ctrl + d : 다음 선택 찾기
ctrl + shift + l : 현재 선택 항목을 모두 선택
ctrl + ]/[ : 라인 들여쓰기/내어쓰기
ctrl + / : 주석 토글
shift + alt + a : 커서 위치에 주석 토글

 

 


 

5. 파이썬 인스타그램 크롤링 이미지 다운로드 beautifulsoup selenium 사용법

 

https://www.youtube.com/watch?v=j_BW5vNrcxA

 

from urllib.request import urlopen
from urllib.parse import quote_plus
from bs4 import BeautifulSoup
from selenium import webdriver
import time

baseUrl = 'https://www.instagram.com/explore/tags/'
plusUrl = input('검색할 태그를 입력하세요 : ')
url = baseUrl + quote_plus(plusUrl)

driver = webdriver.Chrome()
driver.get(url)

time.sleep(3)

html = driver.page_source
soup = BeautifulSoup(html)

insta = soup.select('.v1Nh3.kIKUG._bz0w')

n = 1
for i in insta:
    print('https://www.instagram.com'+ i.a['href'])
    imgUrl = i.select_one('.KL4Bh').img['src']
    with urlopen(imgUrl) as f:
        with open('./img/' + plusUrl + str(n) + '.jpg', 'wb') as h:
            img = f.read()
            h.write(img)
    n += 1
    print(imgUrl)
    print()

driver.close()

 

 


 

6. 파이썬 자동화 selenium 사용법 브라우저 매크로 프로그램 만들기

 

https://www.youtube.com/watch?v=ZFmTwbRQ0uc

 

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Chrome()
url = 'https://google.com'
driver.get(url)

driver.find_element_by_css_selector('.gLFyf.gsfi').send_keys('파이썬')
driver.find_element_by_css_selector('.gLFyf.gsfi').send_keys(Keys.ENTER)

driver.find_elements_by_css_selector('.LC20lb')[2].click()

 

 


 

7. 파이썬 자동화 셀레니움(selenium) webdriver와 actionchains으로 웹사이트 매크로 제작

 

https://www.youtube.com/watch?v=ZFmTwbRQ0uc

 

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains

import time

driver = webdriver.Chrome()
url = 'https://google.com'
driver.get(url)
driver.maximize_window()
action = ActionChains(driver)

driver.find_element_by_css_selector('#gb_70').click()

action.send_keys('본인아이디').perform()
action.reset_actions()
driver.find_element_by_css_selector('.CwaK9').click()

time.sleep(2)
driver.find_element_by_css_selector('.whsOnd.zHQkBf').send_keys('본인비밀번호')
driver.find_element_by_css_selector('.CwaK9').click()
time.sleep(2)

driver.get('https://mail.google.com/mail/u/0/?ogbl#inbox')
time.sleep(2)

driver.find_element_by_css_selector('.T-I.J-J5-Ji.T-I-KE.L3').click()
time.sleep(1)

send_buton = driver.find_element_by_css_selector('.gU.Up')

(
action.send_keys('보낼메일주소').key_down(Keys.ENTER).pause(2).key_down(Keys.TAB)
.send_keys('제목입니다.').pause(2).key_down(Keys.TAB)
.send_keys('abcde').pause(2).key_down(Keys.ENTER)
.key_down(Keys.SHIFT).send_keys('abcde').key_up(Keys.SHIFT).pause(2)
.move_to_element(send_buton).click()
.perform()
)

 

 


 

8. 파이썬 selenium 셀레니움 팝업창 닫는 방법

 

https://www.youtube.com/watch?v=sWTvgJhJ1oQ

 

from selenium import webdriver
import time

# url = 'https://naver.com'
url = 'http://www.lottemart.com'

driver = webdriver.Chrome()
driver.get(url)

print(driver.window_handles)

time.sleep(1)
driver.switch_to_window(driver.window_handles[1])
driver.close()

driver.switch_to_window(driver.window_handles[0])
driver.find_element_by_class_name('logo-toysrus').click()

 

 


 

9. 파이썬 여러페이지 크롤링 네이버 블로그 검색결과 웹스크래핑

 

https://www.youtube.com/watch?v=8Sz8Ek46qGI

 

import urllib.request
import urllib.parse
from bs4 import BeautifulSoup

plusUrl = urllib.parse.quote_plus(input('검색어를 입력하세요:'))

pageNum = 1
count = 1

i = input('몇페이지 크롤링 할까요? : ')

lastPage = int(i) * 10 - 9
while pageNum < lastPage + 1:
    url = f'https://search.naver.com/search.naver?date_from=&date_option=0&date_to=&dup_remove=1&nso=&post_blogurl=&post_blogurl_without=&query={plusUrl}&sm=tab_pge&srchby=all&st=sim&where=post&start={pageNum}'

    html = urllib.request.urlopen(url).read()
    soup = BeautifulSoup(html, 'html.parser')

    title = soup.find_all(class_='sh_blog_title')

    print(f'-----{count}페이지 결과입니다.-----')
    for i in title:
        print(i.attrs['title'])
        print(i.attrs['href'])
    print()
        
    pageNum += 10
    count += 1

 

 


 

10. 파이썬 크롤링 csv 파일저장 방법 네이버 모바일 검색결과 웹스크래핑

 

import csv
from urllib.request import urlopen
from urllib.parse import quote_plus
from bs4 import BeautifulSoup
search = input('검색어를 입력하세요. : ')
url = f'https://m.search.naver.com/search.naver?where=m_view&sm=mtb_jum&query={quote_plus(search)}'
html = urlopen(url).read()
soup = BeautifulSoup(html, 'html.parser')

total = soup.select('.api_txt_lines.total_tit')
searchList = []

for i in total:
    temp = []
    temp.append(i.text)
    temp.append(i.attrs['href'])
    searchList.append(temp)

f = open(f'{search}.csv', 'w', encoding='utf-8', newline='')
csvWriter = csv.writer(f)
for i in searchList:
    csvWriter.writerow(i)

f.close()

print('완료되었습니다.')

 

 


 

11. 파이썬 강의 텍스트 파일 open 읽기 쓰기 추가하기 w, r, a 모드(with 포함)

 

# f = open('text.txt','w',encoding='utf-8')
# f.write('테스트입니다.')
# f.close()


# i = ['사과\n','포도\n','딸기\n']

# f = open('text.txt','a',encoding='utf-8')
# f.writelines(i)
# f.close()


# f = open('text.txt','r',encoding='utf-8')
# data = f.readlines()
# for i in data:
#     print(i,end='')
# f.close()

with open('text.txt','r',encoding='utf-8') as f:
    data = f.readline()
    print(data)

print('끝났습니다.')
line = f.readlines()
print(line)

 

 

 

 

Related posts

Leave a Comment