# 필요한 패키지
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import requests
import time
import urllib.request
from urllib.request import urlretrieve
import os
# 크롤링 웹사이트 오픈
opener = urllib.request.build_opener()
opener.addheaders = [('User-Agent', 'MyApp/1.0')] # 봇 차단을 방지하기위한 헤더
urllib.request.install_opener(opener)
url = '*censored*' # img 를 크롤링 할 url
driver = webdriver.Chrome('C:/Users/wjdrl/Documents/chromedriver')
driver.get(url) # url 접속
time.sleep(1)
dcimg = driver.find_elements_by_css_selector("img.img-responsive") # img css 태그를 달고있는 이미지를 find
list = []
for img in dcimg:
list.append(img.get_attribute('src')) # find 한 이미지의 속성값을 얻어, list 에 추가함
# 저장 폴더 지정
path_folder = 'C:/Users/wjdrl/Desktop/dasd/'
if not os.path.isdir(path_folder):
os.mkdir(path_folder)
i = 0
for link in list: # list 에 있는 이미지 속성값을 link에 차례대로 추가
i += 1 # 같은 이름으로 저장되지않게 하는 반복문
urlretrieve(link, path_folder + f'{i}.jpg') # link에 저장된 이미지를 os에서 설정한 폴더에 자동으로 저장
print(f'{i}번 저장!')
Work-In-Process
아래에 있는 소스코드는 파쿠리해온건데 셀레니움은 안쓰는거같음
import requests
from bs4 import BeautifulSoup
import time
from os.path import getsize
import os
def image_download(BASE_URL):
# 헤더 설정 (필요한 대부분의 정보 제공 -> Bot Block 회피)
headers = {
"Connection" : "keep-alive",
"Cache-Control" : "max-age=0",
"sec-ch-ua-mobile" : "?0",
"DNT" : "1",
"Upgrade-Insecure-Requests" : "1",
"User-Agent" : "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36",
"Accept" : "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
"Sec-Fetch-Site" : "none",
"Sec-Fetch-Mode" : "navigate",
"Sec-Fetch-User" : "?1",
"Sec-Fetch-Dest" : "document",
"Accept-Encoding" : "gzip, deflate, br",
"Accept-Language" : "ko-KR,ko;q=0.9"
}
res = requests.get(BASE_URL, headers=headers)
html = res.text
soup = BeautifulSoup(html, 'html.parser')
# 아래 이미지 다운로드 받는 곳에서 시작
image_download_contents = soup.select("div.appending_file_box ul li")
for li in image_download_contents:
img_tag = li.find('a', href=True)
img_url = img_tag['href']
file_ext = img_url.split('.')[-1]
#저장될 파일명
savename = img_url.split("no=")[2]
headers['Referer'] = BASE_URL
response = requests.get(img_url, headers=headers)
path = f"Image/{savename}"
file_size = len(response.content)
if os.path.isfile(path): #이름이 똑같은 파일이 있으면
if getsize(path) != file_size: #받을 파일과 기존파일의 크기가 다를경우 (다른 파일일경우)
print("이름은 겹치는 다른파일입니다. 다운로드 합니다.")
file = open(path + "[1]", "wb") #경로 끝에 [1] 을 추가해 받는다.
file.write(response.content)
file.close()
else:
print("동일한 파일이 존재합니다. PASS")
else:
file = open(path , "wb")
file.write(response.content)
file.close()
def image_check(text):
text = str(text)
if "icon_pic" in text:
return True
else:
return False
while True:
BASE_URL = "https://gall.dcinside.com/mgallery/board/lists/?id=onshinproject"
# 헤더 설정 (필요한 대부분의 정보 제공 -> Bot Block 회피)
headers = {
"Connection" : "keep-alive",
"Cache-Control" : "max-age=0",
"sec-ch-ua-mobile" : "?0",
"DNT" : "1",
"Upgrade-Insecure-Requests" : "1",
"User-Agent" : "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36",
"Accept" : "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
"Sec-Fetch-Site" : "none",
"Sec-Fetch-Mode" : "navigate",
"Sec-Fetch-User" : "?1",
"Sec-Fetch-Dest" : "document",
"Accept-Encoding" : "gzip, deflate, br",
"Accept-Language" : "ko-KR,ko;q=0.9"
}
res = requests.get(BASE_URL, headers=headers)
if res.status_code == 200:
html = res.text
soup = BeautifulSoup(html, 'html.parser')
#print(soup)
doc = soup.select("td.gall_tit > a:nth-child(1)")
for i in range(4,len(doc)): #공지사항 거르고 시작 (인덱스 뒤부터)
link = "https://gall.dcinside.com" + doc[i].get("href") #글 링크
title = doc[i].text.strip() # 제목
image_insert = image_check(doc[i]) #이미지 포함여부
print(link, title, image_insert)
if(image_insert == True): #이미지 포함시
image_download(link) #이미지 다운로드하기
# break #바로 break해서 첫글만 가져옴
time.sleep(0.5)
'잡동사니' 카테고리의 다른 글
gather id (0) | 2023.02.21 |
---|---|
automatically post at dcinside (0) | 2023.02.10 |
auto guestbook 23.02.11 fixed (0) | 2022.05.10 |
개구리 (0) | 2022.05.09 |