2017-05-14 5 views
1

내가 파이썬의 셀레늄 웹 드라이버 (크롬)파이썬 셀레늄 웹 드라이버

내가 여러 드라이버를 사용하여 각 드라이버 크롤에게 이미지를 가질 수 있습니다 이미지를 크롤링 무엇입니까?

나는

소스 코드

def crawl(searchText): 
    driver = webdriver.Chrome('C:\\Users\\HYOWON\\Desktop\\Desktop\\Graduation\\Code\\Crawling\\chromedriver.exe') 

    searchUrl = "https://www.google.com/search?q={}&site=webhp&tbm=isch".format(searchText) 

    driver.get(searchUrl) 

    imgs_urls = [] # Url 저장 배열 
    cnt = 0 

    for j in range(20): 
    element = driver.find_element_by_css_selector("div[data-ri = '" + str(cnt + j) + "'] img") 
     element.click() 
     sleep(1) 

     soup = create_soup() 

     for img in soup.find_all('img'): 
      try: 
       if img['src'].startswith('http') and img['src'].endswith('jpg'): 
        imgs_urls.append(img['src']) 
      except: 
       pass 

    driver.close() 
    return(imgs_urls) 

을 여러 처리와 수정 코드

실제로
def crawl(): 
    imgs_urls = [] 
    for j in range(50): 
     element1 = driver1.find_element_by_css_selector("div[data-ri = '" + str(cnt) + "'] img") 
     element2 = driver2.find_element_by_css_selector("div[data-ri = '" + str(cnt) + "'] img") 
     element3 = driver3.find_element_by_css_selector("div[data-ri = '" + str(cnt) + "'] img") 

     element1.click() 
     WebDriverWait(driver1, 1) 
     soup1 = create_soup(driver1) 

     for img in soup1.find_all('img'): 
      try: 
       if img['src'].startswith('http') and img['src'].endswith('jpg'): # http로 시작 jpg로 끝나는것만 
       imgs_urls.append(img['src']) 
      except: # 예외 pass 
       pass 

     element2.click() 
     WebDriverWait(driver2, 1) 
     soup2 = create_soup(driver2) 

     for img in soup2.find_all('img'): 
      try: 
       if img['src'].startswith('http') and img['src'].endswith('jpg'): 
       imgs_urls.append(img['src']) 
      except: # 예외 pass 
       pass 

     element3.click() 
     WebDriverWait(driver3, 1) 
     soup3 = create_soup(driver3) 


     for img in soup3.find_all('img'): 
      try: 
       if img['src'].startswith('http') and img['src'].endswith('jpg'): 
       imgs_urls.append(img['src']) 
      except: # 예외 pass 
       pass 

     cnt += 3 

    return (imgs_urls) 

def download_img(url, filename): 
    full_name = str(filename) + ".jpg" 
    urllib.request.urlretrieve(url, 'C:/Python/' + full_name) 

for url in crawl(): 
    download_img(url, filename) 
+0

실제 다중 처리 대기열을 구현해야합니다. 셀레늄은 블로킹이 파이썬이 다른 일을하지 못하도록한다는 의미입니다. 드라이버 1은 페이지를 요청하고 드라이버 2는 드라이버 1이 완료 될 때까지 아무 것도 할 수 없습니다. 이것은 다중 처리 라이브러리로 해결됩니다. – eusid

답변

0

당신이 수를 다음과 같은 일을 할! 나는 현재 일하고있는 현재 프로젝트에 멀티 드라이버 솔루션을 사용하는 것에 대해 생각 해왔다.

이 예제에서는 개별적으로 드라이버 개체를 개별적으로 선언하고 있습니다. 개인적으로는 그들을 일종의 배열에 넣어 더 쉽게 참조 할 수 있도록하고 싶기 때문에 직접 반복 할 수 있습니다. 당연히 이것은 코드의 구조를 약간 다르게 만들지 만 여기서는 너무 많은 문제를 다루지 않아야합니다.

from selenium import webdriver 
from selenium.webdriver.chrome.options import Options 
from selenium.webdriver.common.keys import Keys 
from selenium.webdriver.common.by import By 
from selenium.webdriver.support.ui import WebDriverWait 
from selenium.webdriver.support import expected_conditions as EC 

baseURL_1 = "http://www.stackoverflow.com/" 
baseURL_2 = "http://www.google.com/" 

def main(): 
    init() 
    initialPage() 
    return 

def init(): 
    global drv1 
    global drv2 

    chromedrvPath = "C:\\path_to_chrome\\chromedriver.exe" 
    opt = webdriver.ChromeOptions() 
    opt.add_experimental_option('prefs', { 
     'credentials_enable_service': False, 
     'profile': { 
      'password_manager_enabled': False 
     } 
    }) 
    drv1 = webdriver.Chrome(chromedrvPath,chrome_options=opt) 
    drv2 = webdriver.Chrome(chromedrvPath,chrome_options=opt) 

    return 

def initialPage(): 
    navigate(baseURL_1,1) 
    navigate(baseURL_2,2) 
    return 

def navigate(URL,d): 
    if(d == 1): 
     drv1.get(URL) 
    if(d == 2): 
     drv2.get(URL) 
    return 

if __name__ == "__main__": 
    main() 
+0

고맙습니다. 내 방식으로 위의 코드를 수정하려고하는데 403 오류가 발생합니다. 해결할 수 있습니까? ** 수정 코드 **를 참조하십시오. –

관련 문제