我正在尝试访问一个类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 niskokalorycznynapójgazowany 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”)'访问类有什么区别?结果相同吗?
任何帮助将不胜感激。
答案 0 :(得分:1)
findAll返回在定义的标记中找到的项目的列表。想象一下,如果有多个标签,它将返回匹配的多个标签的列表。
无论您使用findAll("a", class_="current-page")
还是传递带有多个参数{'class' : 'current-page'}
的字典,都应该没有任何区别。我可能错了,但我相信,因为其中一些方法是从早期版本继承的。
您可以通过选择元素并获取如下所示的text属性来从返回的对象中提取文本:
products_links = soup.findAll("a", {'class' : 'current-page'}, text = True)
print(products_links[0].text)