CES 2024 혁신상 수상 제품/서비스에 대한 정보를 웹 크롤링

#문과생도AI #4주차발표

단톡방 슬로앤스테디님의 궁금해하신 내용에 대해 작성을 해보았는데, 슬로앤스테디님에게 허락을 받지못하고 올려서 걱정입니다.
이른아침님이나 슬로앤스테디님도 이미 완료하셨고, 저보다 좋게 작성하셨을겁니다.

최근 클로드가 성능이 좋다고 해서 활용을 해보았습니다. 처음에 출력결과물에 대한 화면캡처를 못했습니다.

항상 첫질문을 통해 시작합니다.



오류가 발생해서 클로드와 몇차례의 수정작업을 했습니다.

몇차례 시도해보았지만 잘안되었습니다.

출력이되더라도 글자처리가 안되었습니다.


그리고 화면에 보이는 것만 처리되었는데, 스크롤다해보니 아래에도 제품들이 있었습니다.



출력결과가 만족스럽지 못해 다시 물어보았습니다

그래서 X-path와 HTML모두 제시를 하였습니다

동작이 잘되나 중간에 에러가 발생했습니다


471개 물건이 너무 많아 10개 테스트를 하도록 조정했습니다

다음이 csv로 출력하는 최종 코딩입니다



def get_product_links(url, max_links=10):

try:

service = Service(ChromeDriverManager().install())

driver = webdriver.Chrome(service=service)

driver.get(url)

# 페이지가 로드될 때까지 대기

WebDriverWait(driver, 10).until(

EC.presence_of_element_located((By.CSS_SELECTOR, "a[href*='/Innovation-Awards/Honorees/']"))

)

product_links = []

while len(product_links) < max_links:

# 현재 페이지에서 링크 추출

elements = driver.find_elements(By.CSS_SELECTOR, "a[href*='/Innovation-Awards/Honorees/']")

for element in elements:

href = element.get_attribute('href')

if href and '/Innovation-Awards/Honorees/' in href:

parsed_url = urllib.parse.urlparse(href)

encoded_path = urllib.parse.quote(parsed_url.path)

encoded_url = parsed_url._replace(path=encoded_path).geturl()

if encoded_url not in product_links:

product_links.append(encoded_url)

if len(product_links) >= max_links:

break

if len(product_links) >= max_links:

break

# 필요한 만큼만 스크롤

driver.execute_script("window.scrollBy(0, 500);")

time.sleep(1) # 스크롤 후 잠시 대기

print(f"Found {len(product_links)} product links.")

return product_links[:max_links]

except Exception as e:

print(f"An error occurred while fetching the page: {e}")

return []

finally:

driver.quit()

def main():

base_url = "https://www.ces.tech/innovation-awards/honorees.aspx"

product_links = get_product_links(base_url, max_links=10)

if not product_links:

print("No product links found. Exiting.")

return

with open('ces_2024_innovation_awards_test.csv', 'w', newline='', encoding='utf-8') as file:

writer = csv.writer(file)

writer.writerow(['Product Name', 'Category', 'Sub-Category', 'Description', 'Product URL']) # 헤더

for i, link in enumerate(product_links, 1):

print(f"Processing link {i} of {len(product_links)}: {link}")

product_info = get_product_info(link)

if product_info:

writer.writerow(product_info)

else:

print(f"Failed to get info for link: {link}")

# 서버에 과도한 부하를 주지 않기 위해 요청 간 간격을 둡니다

time.sleep(1)

print("Finished processing test links. Results saved to 'ces_2024_innovation_awards_test.csv'.")

if name == "__main__":

main()


동작화면을 보시면 아시겠지만 시간이 많이 걸리네요..

2024-07-01 12-40-44.mkv

지피터스 단톡방에서 codepen사용하는 것을 보았는데, 이것이 어떤지 보려고 적용해보았습니다.


import time

import urllib.parse

from selenium import webdriver

from selenium.webdriver.common.by import By

from selenium.webdriver.support.ui import WebDriverWait

from selenium.webdriver.support import expected_conditions as EC

from selenium.webdriver.chrome.service import Service

from webdriver_manager.chrome import ChromeDriverManager

def get_product_links(url, max_links=10):

# 이전과 동일한 함수 내용

# ...

def get_product_info(url):

# 이전과 동일한 함수 내용

# ...

def generate_html_table(products):

html = """

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>CES 2024 Innovation Awards</title>

<style>

table {

border-collapse: collapse;

width: 100%;

}

th, td {

border: 1px solid #ddd;

padding: 8px;

text-align: left;

}

th {

background-color: #f2f2f2;

}

tr:nth-child(even) {

background-color: #f9f9f9;

}

</style>

</head>

<body>

<h1>CES 2024 Innovation Awards</h1>

<table>

<tr>

<th>Product Name</th>

<th>Category</th>

<th>Sub-Category</th>

<th>Description</th>

<th>Product URL</th>

</tr>

"""

for product in products:

html += f"""

<tr>

<td>{product[0]}</td>

<td>{product[1]}</td>

<td>{product[2]}</td>

<td>{product[3]}</td>

<td><a href="{product[4]}" target="_blank">Link</a></td>

</tr>

"""

html += """

</table>

</body>

</html>

"""

return html

def main():

base_url = "https://www.ces.tech/innovation-awards/honorees.aspx"

product_links = get_product_links(base_url, max_links=10)

if not product_links:

print("No product links found. Exiting.")

return

products = []

for i, link in enumerate(product_links, 1):

print(f"Processing link {i} of {len(product_links)}: {link}")

product_info = get_product_info(link)

if product_info:

products.append(product_info)

else:

print(f"Failed to get info for link: {link}")

time.sleep(1)

html_content = generate_html_table(products)

with open('ces_2024_innovation_awards.html', 'w', encoding='utf-8') as file:

file.write(html_content)

print("Finished processing test links. Results saved to 'ces_2024_innovation_awards.html'.")

print("You can now copy the content of this HTML file to CodePen.")

if name == "__main__":

main()


Insight

  1. 크롤링하려면 해당싸이트의 구조를 세부적으로 파악해보면 시간을 단축할 수 있겠다

  2. Selenium을 잘 활용해서 로그인을 요구되는 싸이트를 자동화도 가능할 것 같다.

3
4개의 답글

👉 이 게시글도 읽어보세요