gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 08:53:55 24 4
gpt4 key购买 nike

我正在尝试访问一类 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com