인프런 영문 브랜드 로고
인프런 영문 브랜드 로고

인프런 커뮤니티 질문&답변

초칼라님의 프로필 이미지

작성한 질문수

[신규 개정판] 이것이 진짜 크롤링이다 - 실전편 (인공지능 수익화)

데이터 추출하기 (복잡한 HTML 구조)

Link를 엑셀로 저장할 때 하이퍼링크 되도록 저장 방법 문의

작성

·

528

답변 2

0

스타트코딩님의 프로필 이미지
스타트코딩
지식공유자

image

link 저장할 때 HYPERLINK 함수를 빼셔야 합니다~

 

# 셀레니움 기본 템플릿 templates
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
import time
import pyperclip
import pyautogui
from bs4 import BeautifulSoup

# 크롬 드라이버 생성
driver = webdriver.Chrome()

# search_text = pyautogui.prompt("검색어를 입력하세요.")
search_text = "닭가슴살"

# 페이지 이동
url = f"https://search.shopping.naver.com/search/all?query={search_text}"
driver.get(url)

# scroll 전 높이 확인
last_height = driver.execute_script("return document.body.scrollHeight")

while True:
    # 스크롤 끝까지 내리기
    driver.execute_script("window.scrollTo(0, document.body.scrollHeight)")
    time.sleep(0.5)
    # 스크롤 후 높이
    current_height = driver.execute_script("return document.body.scrollHeight")

    # 비교
    if last_height == current_height:
        break

    # 스크롤 전 높이 Update
    last_height = current_height

import pandas as pd

# 상품명, 상세페이지링크, 가격 추출하기
html = driver.page_source
soup = BeautifulSoup(html, 'html.parser')

data = []

items = soup.select(".product_item__MDtDF")
for item in items:
    name = item.select_one('.product_title__Mmw2K > a').text
    link = item.select_one('.product_title__Mmw2K > a').attrs['href']
    # link = item.select_one('.product_title__Mmw2K > a').attrs['href']
    print(len(link))
    # strip() : 앞뒤 공백 제거
    # soup.select_one('.product-price').text.strip()
    price = int(item.select_one('.price_num__S2p_v').text.split('원')[0].replace(',',''))
    print(name, price, link)  
    data.append([name, price, link])  

df = pd.DataFrame(data, columns=["상품명", "가격", "상세페이지링크"])

df.to_excel("output.xlsx", index=False, engine='xlsxwriter')

0

스타트코딩님의 프로필 이미지
스타트코딩
지식공유자

pip install xlsxwriter 를 하고

engine 을 xlsxwriter로 지정해 보시겠어요?

 

df.to_excel("output.xlsx", index=False, engine='xlsxwriter')
초칼라님의 프로필 이미지
초칼라
질문자

동일하게 에러가 발생합니다.

 

=======================

코딩 내용

=======================

 

# 셀레니움 기본 템플릿 templates
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
import time
import pyperclip
import pyautogui
from bs4 import BeautifulSoup

# 크롬 드라이버 생성
driver = webdriver.Chrome()

# search_text = pyautogui.prompt("검색어를 입력하세요.")
search_text = "닭가슴살"

# 페이지 이동
url = f"https://search.shopping.naver.com/search/all?query={search_text}"
driver.get(url)

# scroll 전 높이 확인
last_height = driver.execute_script("return document.body.scrollHeight")

while True:
    # 스크롤 끝까지 내리기
    driver.execute_script("window.scrollTo(0, document.body.scrollHeight)")
    time.sleep(0.5)
    # 스크롤 후 높이
    current_height = driver.execute_script("return document.body.scrollHeight")

    # 비교
    if last_height == current_height:
        break

    # 스크롤 전 높이 Update
    last_height = current_height

import pandas as pd

# 상품명, 상세페이지링크, 가격 추출하기
html = driver.page_source
soup = BeautifulSoup(html, 'html.parser')

data = []

items = soup.select(".product_item__MDtDF")
for item in items:
    name = item.select_one('.product_title__Mmw2K > a').text
    link = '=HYPERLINK("' + item.select_one('.product_title__Mmw2K > a').attrs['href'] + '","링크")'
    # link = item.select_one('.product_title__Mmw2K > a').attrs['href']
    print(len(link))
    # strip() : 앞뒤 공백 제거
    # soup.select_one('.product-price').text.strip()
    price = int(item.select_one('.price_num__S2p_v').text.split('원')[0].replace(',',''))
    print(name, price, link)  
    data.append([name, price, link])  

df = pd.DataFrame(data, columns=["상품명", "가격", "상세페이지링크"])

df.to_excel("output.xlsx", index=False, engine='xlsxwriter')