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

使用BeautifulSoup时触发Expression expected错误,求解决方案

问题解决

错误原因

  • class是Python的保留关键字,不能直接作为find_all()的参数名,这是触发Expression expected和Identifier expected错误的核心原因。BeautifulSoup中需使用class_(带下划线后缀)来指定CSS类名。
  • 代码里的article.find('p5')属于笔误,HTML标准中不存在p5标签,应改为p标签。

修正后的代码

from bs4 import BeautifulSoup
import requests


def get_guide():
    headers = {
        'user-agent': "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36"
    }

    url = 'https://start.tpu.ru/guide/1'
    r = requests.get(url=url, headers=headers)

    soup = BeautifulSoup(r.text,'lxml')
    # 替换class为class_作为参数名
    articles_cards = soup.find_all("div", class_ = "guide-box")

    for article in articles_cards:
        article_title = article.find('h5').text.strip()
        # 修正p5为p标签
        article_desc = article.find('p').text.strip()

        print(f'{article_title}|{article_desc}')

get_guide()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 23:15:50