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

集成Gumtree.Au解析器的Telegram Bot无法启动,求技术支持

Gumtree.au解析Telegram Bot启动失败排查与修复

核心启动错误:语法错误

代码中初始化Bot的行存在单引号嵌套问题,这是导致程序无法启动的直接原因:

bot = telebot.TeleBot('I won't show you the Api')

修复方案:改用双引号包裹字符串,或转义内部单引号:

# 方案1:双引号包裹
bot = telebot.TeleBot("I won't show you the Api")
# 方案2:转义单引号
bot = telebot.TeleBot('I won\'t show you the Api')

解析逻辑中的潜在崩溃点

即使修复语法错误,解析Gumtree页面时也可能因元素不存在抛出异常,导致Bot运行中断:

  • 当ad.find()找不到目标元素时,直接调用.text或取索引会触发TypeError
  • 转换价格、浏览量为数值时,若格式不符合预期会触发ValueError

修复方案:添加空值判断和异常捕获,避免程序崩溃:

def parse_gumtree():
    url = 'https://www.gumtree.com.au/s-stuff-for-sale/page-1/'
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
                      'Chrome/58.0.3029.110 Safari/537.3'}
    response = requests.get(url, headers=headers)
    soup = BeautifulSoup(response.content, 'html.parser')

    products = []
    for ad in soup.find_all('div', class_='user-ad-card-new-design'):
        # 先获取所有目标元素,判断是否存在
        title_tag = ad.find('a', class_='gallery-listing__thumb')
        price_tag = ad.find('span', class_='gallery-listing__price-currency')
        views_tag = ad.find('span', class_='vip-ad-header__views')
        image_tag = ad.find('img', class_='user-ad-image')
        
        if not all([title_tag, price_tag, views_tag, image_tag]):
            continue
            
        try:
            title = title_tag['aria-label']
            price = price_tag.text.strip()
            views = views_tag.text.strip()
            image_url = image_tag['src']
            
            # 转换数值时捕获格式异常
            view_count = int(views)
            price_value = float(price.replace('$', '').replace(',', ''))
            
            if view_count > 0 and price_value <= 1000:
                product = {
                    'title': title,
                    'price': price,
                    'views': views,
                    'image_url': image_url
                }
                products.append(product)
        except (ValueError, KeyError):
            # 跳过格式异常的广告条目
            continue

    return products

其他必要检查

  • 确认已安装所有依赖:执行pip install requests beautifulsoup4 pytelegrambotapi
  • 检查Bot Token是否有效,确保已通过@BotFather完成Bot创建
  • 若Gumtree拦截请求,可尝试补充Accept-Language等请求头,或使用代理IP

内容的提问来源于stack exchange,提问作者Sweet Bonanza

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 00:23:13