-
카테고리
-
세부 분야
데이터 분석
-
해결 여부
미해결
같은 코드인데 크롤링 하는 갯수가 실행마다 다릅니다.
21.06.25 20:57 작성 조회수 111
0
import requests
from bs4 import BeautifulSoup
from selenium import webdriver
from urllib.request import urlopen
from selenium.webdriver.common.by import By
browser = webdriver.Chrome()
browser.maximize_window()
url = "https://www.google.com/search?q=%EC%82%AC%EA%B3%BC&sxsrf=ALeKk03BqEA7aHRUtvEA6hE14DpJIdLTNg:1624619249906&source=lnms&tbm=isch&sa=X&ved=2ahUKEwiQmqSq0rLxAhWSNKYKHco2CUQQ_AUoAXoECAEQAw&biw=958&bih=959"
browser.get(url)
soup = BeautifulSoup(browser.page_source, "lxml")
imgs = soup.find_all("div", attrs={"class":"isv-r PNCib MSM1fd BUooTd"})
print(len(imgs))
for idx, image in enumerate(imgs):
print(idx)
image = imgs[idx].find("img", attrs={"class":"rg_i Q4LuWd"})
name = image.get('src')
if name == None:
continue
if name.startswith("http"):
image_res = requests.get(name)
image_res.raise_for_status()
with open("apple{}.jpg".format(idx+1), "wb") as h:
h.write(image_res.content)
else:
with urlopen(name) as f:
with open("apple{}.jpg".format(idx+1), "wb") as h:
img_src = f.read()
h.write(img_src)
browser.quit()
selenium을 통해 browser를 열고 html을 가져오는 방식을 이용했습니다.
구글 사과 이미지를 다운받는 코드를 작성했는데 실행마다 저장하는 이미지 갯수가 다릅니다.
그리고 image속성의 src가 모두 들어있는데 가끔 'src'를 찾을 수 없다는 error가 발생해서
if문으로 src속성값에 따라 분기처리를 했습니다.
왜 이런 상황이 발생하는지 알려주실 수 있나요??
답변을 작성해보세요.
답변 0