It looks like the issue with your current script is that the title variable is not correctly associated with each individual car image. Instead, you're retrieving all titles on the page and then setting the title variable inside a loop, which causes only the last title to be used for all images.
To fix this, you should pair each image with its corresponding title. This can be achieved by iterating over both img_tags and titles simultaneously using the zip function. Alternatively, if the HTML structure allows, you can find a common parent element for each image and title, ensuring they are correctly matched.
Here's how you can modify your script to correctly associate each title with its corresponding image:
Updated Code
from selenium import webdriver
from bs4 import BeautifulSoup
import time
import urllib.request
import os
def millis():
return int(round(time.time() * 1000))
# Change root path to save the data
root = "C:\\Users\\PC\\Documents\\cars-webscrape\\Data" # Use double backslashes or raw string for Windows paths
# Car search parameters
car_name = "toyota"
model_year_range = "2018-2020" # Filter cars between 2018-2020
price_limit = 5000 # Maximum price limit
buy_it_now = "true" # Only buy it now cars
# Initialize the WebDriver (make sure the ChromeDriver path is set if not in PATH)
driver = webdriver.Chrome()
def get_car(car_name, model_year_range, price_limit, buy_it_now):
count = 0
for i in range(1, 6): # Pages usually start from 1
# Construct the URL with the new filters
url = (
f"https://www.copart.com/lotSearchResults/?free=true&query={car_name}"
f"&year={model_year_range}&price={price_limit}&buyItNow={buy_it_now}&page={i}"
)
driver.get(url)
time.sleep(3) # Increased sleep time for better page load
content = driver.page_source
soup = BeautifulSoup(content, 'lxml')
# Find all car listing containers (adjust the selector based on actual HTML structure)
# Assuming each car listing is within a div with a specific class
car_containers = soup.find_all('div', class_='search-result-table') # Update the class name as needed
for container in car_containers:
# Extract the image
img_tag = container.find('img', alt='Lot Image')
if not img_tag:
continue # Skip if no image found
imgsrc = img_tag.get('src')
if not imgsrc:
continue # Skip if no src found
# Extract the title
title_tag = container.find('span', class_='search_result_lot_detail ng-star-inserted')
if not title_tag:
title = "No_Title"
else:
title = title_tag.get_text(strip=True).replace(" ", "-")
# Generate unique filename
val = millis()
count += 1
# Create folder for images
directory = os.path.join(root, title)
if not os.path.exists(directory):
os.makedirs(directory)
filename = f"{title}-{val}.jpg"
saveimageDir = os.path.join(directory, filename)
try:
# Save the image
urllib.request.urlretrieve(imgsrc, saveimageDir)
print(f"Image saved: {filename}")
except Exception as e:
print(f"Error saving image {filename}: {e}")
print(f"Total images saved till now: {count}")
time.sleep(2) # Wait before moving to the next page
# Execute the scraping function
get_car(car_name, model_year_range, price_limit, buy_it_now)
# Quit the WebDriver
driver.quit()
Explanation of Changes
-
Associating Titles with Images:
- Original Issue: The original code fetched all titles on a page and then looped through them inside the image loop, which resulted in only the last title being used for all images.
- Solution: Instead of fetching all titles separately, find each title within the same container as the image. This ensures that each image is paired with its corresponding title.
-
Finding the Correct HTML Elements:
- Assumption: Each car listing is contained within a specific parent
<div>. You need to inspect the actual HTML structure of copart.com to find the correct parent container class or identifier.
- Implementation: Replace
'div', class_='search-result-table' with the actual class or identifier that wraps each car listing.
-
Handling Missing Data:
- Added checks to skip images or titles if they're not found to prevent the script from breaking.
-
Improved URL Construction:
- Adjusted the page index to start from 1, assuming pagination starts at page 1. Verify this based on the actual website.
-
Increased Sleep Time:
- Increased
time.sleep durations to ensure the page loads completely, which can be crucial for dynamically loaded content.
-
Path Handling:
- Ensure that the root path uses double backslashes (
\\) or use a raw string (prefix with r) to avoid escape sequence issues in Windows paths.
-
Error Handling:
- Improved error messages to include which image failed to save.
Additional Recommendations
-
Dynamic Content Loading:
- If
copart.com uses infinite scrolling or loads content dynamically as you scroll, you might need to implement scrolling in Selenium to load all car listings.
-
Using Explicit Waits:
- Instead of using
time.sleep, consider using Selenium’s explicit waits (WebDriverWait) to wait for specific elements to load, making the script more efficient and reliable.
-
Rate Limiting:
- Be mindful of the website’s terms of service and implement rate limiting to avoid being blocked.
-
Headless Browsing:
-
Logging:
- Implement proper logging instead of
print statements for better monitoring and debugging.
By making these changes, each image should now be correctly associated with its respective car title, ensuring that images are saved in the correct directories with appropriate filenames.