【问题标题】:Use get_text() for only one HTML class - Python, BeautifulSoup仅对一个 HTML 类使用 get_text() - Python、BeautifulSoup
【发布时间】:2026-01-17 18:25:02
【问题描述】:

我正在尝试访问一类 HTML 中的唯一文本。我尝试申请documentationBeautifulSoup,但我总是收到相同的错误消息或此标签中的所有项目。

我的代码.py

from urllib.request import urlopen
from bs4 import BeautifulSoup
import requests
import re

url = "https://www.auchandirect.pl/auchan-warszawa/pl/pepsi-cola-max-niskokaloryczny-napoj-gazowany-o-smaku-cola/p-98502176"
r = requests.get(url, headers={'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'}, timeout=15)
html = urlopen(url)
soup = BeautifulSoup(html, 'lxml')
type(soup)

products_links = soup.findAll("a", {'class' : 'current-page'})

print(products_links)

在结果中,我只需要这个“Max niskokaloryczny napój gazowany o smaku cola”。

我的结果是:

<a class="current-page" href="/auchan-warszawa/pl/pepsi-cola-max-niskokaloryczny-napoj-gazowany-o-smaku-cola/p-98502176"><span>Max niskokaloryczny napój gazowany o smaku cola</span></a>

或者如果我将根据文档应用此代码 (print(products_links.get_text())) Pycharm 返回:

ResultSet object has no attribute '%s'. You're probably treating a list of items like a single item. Did you call find_all() when you meant to call find()?"

如何从“当前页面”中正确提取文本? 为什么函数不返回标签中的文本? 使用 'findAll("a", class_="current-page")' 相对于 'findAll("a", {'class' : 'current-page'})' 访问类有什么区别?结果一样吗?

任何帮助将不胜感激。

【问题讨论】:

    标签: python beautifulsoup


    【解决方案1】:

    findAll 返回在您定义的标签中找到的项目列表。想象一下,如果有多个相同的标签,它会返回匹配的多个标签的列表。

    无论您使用findAll("a", class_="current-page") 还是传递带有多个参数的字典{'class' : 'current-page'},都应该没有任何区别。我可能错了,但我相信因为其中一些方法是从早期版本继承的。

    您可以通过选择元素并获取如下所示的文本属性来从返回的对象中提取文本:

    products_links = soup.findAll("a", {'class' : 'current-page'}, text = True)
    print(products_links[0].text)
    

    【讨论】:

    • 非常感谢您的回答。也许是因为我的英语知识很差,但是在文档中我可以在哪里找到这些信息?你怎么知道使用'text = True'和products_links'.text'元素?能不能理智的解释一下?
    • 没问题。希望它有所帮助。您应该可以在这里获得信息,crummy.com/software/BeautifulSoup/bs3/…**kwargs)。我不认为text = True 是必需的,重要的是您知道findAll 返回与您的参数匹配的对象列表。