You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Autoscout24二手车数据爬取故障求助:无结果且循环无法终止

二手车数据爬取问题排查与修复

问题情况

为二手车分析论文编写了爬取autoscout24.com数据的代码,但本地和Google CoLab均无法获取数据,且循环无法终止;手动访问网站则能正常查看数据。原代码如下:

brand = []
model = []
price = []
total = []
a = 101
k = 100
l = 20000 # calculates between € 0 - € 2.000.000
j = 1
while j <= l:
    i = 1
    website = 'https://www.autoscout24.com/lst?sort=price&desc=0&cy=NL&atype=C&ustate=N%2CU&damaged_listing=exclude&powertype=kw&pricefrom=' + str(a) + '&priceto=' + str(a+k-1) + '&search_id=2gfy6suaasl&page='
    a = a + k
    j = j + 1  
    while i <= 20:
        website = website + str(i)
        response = requests.get(website)
        soup = BeautifulSoup(response.content, 'html.parser')
        results = soup.find_all('div', {'class' : 'ListItem_wrapper__J_a_C'})
        i = i + 1
        for result in results:
            brand.append(result.find('h2').get_text())
            model.append(result.find('span', {'class':'ListItem_version__jNjur'}).get_text())
            price.append(result.find('p', {'class':'Price_price__WZayw'}).get_text().strip())
            total.append(result.find('div', {'class':'VehicleDetailTable_container__mUUbY'}).get_text())

问题分析

  1. URL拼接错误:内层循环每次把页码i直接拼在website变量后面,导致URL不断变长(比如第一次是page=1,第二次变成page=12,第三次变成page=123),请求的都是无效页面,自然拿不到数据。
  2. 外层循环逻辑冗余:设定l=20000完全没必要,从0到2000000欧元,每次步长100,实际只需要20000次循环,但网站根本没有这么多价格区间的页面,过多的循环次数直接导致程序停不下来。
  3. 无反爬处理:直接用requests.get发送请求,没有模拟浏览器的请求头,网站会识别为爬虫,返回空页面或403状态码。
  4. 无异常处理:如果某个车辆的元素(比如版本信息)不存在,调用.get_text()会直接报错中断程序,导致后续数据也无法获取。

修复后的代码

import requests
from bs4 import BeautifulSoup
import time

brand = []
model = []
price = []
total = []
# 价格区间从0开始,步长100,到2000000欧元
start_price = 0
step = 100
max_price = 2000000

# 模拟浏览器请求头,绕过基础反爬
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36'
}

# 遍历所有价格区间
while start_price <= max_price:
    end_price = start_price + step - 1
    # 基础URL,每次循环重新生成,避免拼接错误
    base_url = f'https://www.autoscout24.com/lst?sort=price&desc=0&cy=NL&atype=C&ustate=N%2CU&damaged_listing=exclude&powertype=kw&pricefrom={start_price}&priceto={end_price}&search_id=2gfy6suaasl'
    
    # 遍历分页,最多20页,无数据则提前终止
    for page in range(1, 21):
        url = f'{base_url}&page={page}'
        try:
            response = requests.get(url, headers=headers)
            # 检查请求是否成功
            response.raise_for_status()
            soup = BeautifulSoup(response.content, 'html.parser')
            results = soup.find_all('div', {'class': 'ListItem_wrapper__J_a_C'})
            
            # 当前页无结果,说明该价格区间已无更多数据
            if not results:
                break
            
            for result in results:
                # 品牌,元素不存在则填充N/A
                brand_elem = result.find('h2')
                brand.append(brand_elem.get_text().strip() if brand_elem else 'N/A')
                
                # 型号版本
                model_elem = result.find('span', {'class': 'ListItem_version__jNjur'})
                model.append(model_elem.get_text().strip() if model_elem else 'N/A')
                
                # 价格
                price_elem = result.find('p', {'class': 'Price_price__WZayw'})
                price.append(price_elem.get_text().strip() if price_elem else 'N/A')
                
                # 车辆详情
                total_elem = result.find('div', {'class': 'VehicleDetailTable_container__mUUbY'})
                total.append(total_elem.get_text().strip() if total_elem else 'N/A')
                
            # 添加延迟,避免请求过于频繁被封
            time.sleep(1)
        except Exception as e:
            print(f"请求页面{page}出错: {e}")
            continue
    
    start_price += step

# 打印获取到的数据量
print(f"共获取{len(brand)}条车辆数据")

修复说明

  • 修正URL拼接逻辑,每次分页都基于基础URL生成正确的链接,避免无效请求。
  • 优化价格区间遍历逻辑,从0开始到2000000,步长100,减少无效循环。
  • 添加浏览器请求头,模拟正常用户访问,绕过基础反爬机制。
  • 增加异常处理,单个元素不存在或请求出错时不会中断程序,而是记录错误并继续执行。
  • 添加请求延迟,降低被网站封禁的风险。
  • 当某分页没有数据时,自动跳出该价格区间的分页循环,减少不必要的请求。

内容的提问来源于stack exchange,提问作者Aykut Yücel Günel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 08:59:14