python - 仅对一个 HTML 类使用 get_text() - Python、BeautifulSoup

标签 python beautifulsoup

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

我的代码.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'})' 访问类有什么区别相同的结果?

任何帮助将不胜感激。

最佳答案

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

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

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

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

关于python - 仅对一个 HTML 类使用 get_text() - Python、BeautifulSoup,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52909544/

相关文章:

python - 我们如何在PE文件中的IMAGE_IMPORT_BY_NAME STRUCT中获取提示?

python - 用Python发送请求(用Burp拦截)

python - 需要使用 RegEx 和 BeautifulSoup 查找文本

python - 如何使用 BeautifulSoup 从网页中抓取结构化表格?

python - 如何访问项目根文件夹

python - BaseHTTPServer 和 SimpleHTTPServer 有什么区别?何时何地使用它们?

java - 对 GSM 电话/调制解调器进行编程以调用电话

python - requests.get() 和/或 BeautifulSoup() 行为不一致

python - 嵌入 BS4 元素的 div 类中的背景图像的 URL

javascript - 无法使用 Selenium webdriver、python 在 <span> 标记内模拟 onclick javascript