How to scrape otto.de?

How to scrape otto.de?

The code automates a web scraping task using Selenium, BeautifulSoup, and Python libraries to collect product information (titles and prices) from the German e-commerce website Otto.de. Here's a breakdown of what each section does:

Imports

python
Copy code
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from time import sleep
import csv
from bs4 import BeautifulSoup
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import json
  1. selenium: Automates browser actions.
  2. BeautifulSoup: Parses HTML content.
  3. time.sleep: Adds delays for dynamic page loading.
  4. csv: Writes scraped data into a CSV file.
  5. json: Handles JSON data.
  6. WebDriverWait and EC: Waits for elements to load dynamically.

Initialization

python
Copy code
driver = webdriver.Chrome()
driver.get('https://www.otto.de/')
  1. Launches a Chrome browser instance and navigates to the Otto website.

Accepting Cookies

python
Copy code
WebDriverWait(driver, 60).until(EC.presence_of_element_located((By.ID, "onetrust-accept-btn-handler")))
cookies = driver.find_element(By.ID, "onetrust-accept-btn-handler")
cookies.click()
  1. Waits for the cookie consent popup and clicks "Accept."

Search for Products

python
Copy code
WebDriverWait(driver, 60).until(
EC.presence_of_element_located((By.CSS_SELECTOR, ".squirrel_searchfield.js_squirrel_searchbar__input.svelte-11jrfxz"))
)
search_bar = driver.find_element(By.CSS_SELECTOR, ".squirrel_searchfield.js_squirrel_searchbar__input.svelte-11jrfxz")
search_bar.click()
search_bar.send_keys("football" + Keys.RETURN)
sleep(8)
  1. Locates the search bar, enters the term "football," and submits the search query.

Write CSV File Header

python
Copy code
with open('products.csv', mode='w', newline='', encoding='utf-8') as file:
writer = csv.writer(file)
writer.writerow(['Product Number', 'Product Title', 'Product Price'])
  1. Opens a CSV file and writes the column headers: Product Number, Product Title, and Product Price.

Scrolling and Scraping Products

python
Copy code
initial_height = driver.execute_script("return document.body.scrollHeight")
scroll_position = 0
total_scrolls = 25
for _ in range(total_scrolls):
driver.execute_script(f"window.scrollTo(0, {scroll_position + initial_height / total_scrolls});")
scroll_position += initial_height / total_scrolls
sleep(7 / total_scrolls)
  1. Gradually scrolls down the page to load more products dynamically.

Parsing Product Data

python
Copy code
page_source = driver.page_source
soup = BeautifulSoup(page_source, 'html.parser')
product_elements = soup.find_all('article', attrs={'data-product-listing-type': 'SearchResultPage'})
  1. Fetches the page source and uses BeautifulSoup to locate product elements.

Extracting Product Title and Price

python
Copy code
for idx, product in enumerate(product_elements, 1):
title_element = product.find('p', class_='find_tile__name pl_copy100')
title = title_element.get_text(strip=True) if title_element else 'No Title Found'

price_element = product.find('span', class_='find_tile__retailPrice pl_headline50 find_tile__priceValue')
if not price_element:
price_element = product.find('span', class_='find_tile__retailPrice pl_headline50 find_tile__priceValue find_tile__priceValue--red')
price = price_element.get_text(strip=True) if price_element else 'No Price Found'

writer.writerow([idx, title, price])
  1. Extracts product titles and prices, handling variations in class names for prices.
  2. Writes the data to the CSV file.

Pagination

python
Copy code
nextpage = driver.find_element(By.CSS_SELECTOR,'li#reptile-paging-bottom-next > button').get_attribute('data-page')

if nextpage:
nextpage = json.loads(nextpage)
url = driver.current_url.split("?")[0]
url = f"{url}?l=gq&o={nextpage.get('o')}"
driver.get(url)
else:
break
  1. Checks for the "Next Page" button.
  2. Constructs the URL for the next page using JSON data.
  3. Navigates to the next page or exits the loop if there are no more pages.

Closing the Browser

python
Copy code
driver.quit()
  1. Closes the browser instance after the scraping process is complete.


Key Points

  1. Dynamic Loading: Uses Selenium to handle dynamically loaded content.
  2. Robust Element Selection: Uses WebDriverWait and multiple class checks to ensure elements are located correctly.
  3. CSV Output: Saves scraped data in a structured format.
  4. Pagination Handling: Scrapes multiple pages by detecting and navigating to the next page.



  • Tags:
  • No tags

Comments (0)

Leave a Reply

Log in to post a comment.