【发布时间】: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