gpt4 book ai didi

python - Beautifulsoup .text 函数不返回文本

转载 作者:太空宇宙 更新时间:2023-11-03 21:44:19 25 4
gpt4 key购买 nike

我尝试提取运行代码返回的 h1 标记内的文本,但没有收到任何输出。但是,代码能够找到指定的标签,如下所示:

<h1 class="product-name main-heading">Mixed Brown Rice 2.5kg</h1>

网页链接:

https://giantonline.com.sg/product/mixed-brown-rice-5142760

这是我使用的代码:

driver.get("https://giantonline.com.sg/product/mixed-brown-rice-5142760")
driver.implicitly_wait(30)
time.sleep(4)
bs2=BeautifulSoup(driver.page_source, 'lxml')
for z in bs2.find_all('div',class_="col-md-5 col-sm-5 col-xs-12"):
try:
name = z.find('h1',class_='product-name')
print(type(name))
print(name)
name = name.get_text(seperator=' ')
print(name)
size = z.find('h1',class_='product-size main-heading')
size = size.text
oldprice = z.find('div',class_='old-price')
oldprice = oldprice.text
price = z.find('div',class_='content_price')
price = price.text
except:
continue

为什么我无法从 h1 标记中获取文本?

最佳答案

这应该可以工作,请检查此代码。

from bs4 import BeautifulSoup
html = """<h1 class="product-name main-heading">Mixed Brown Rice 2.5kg</h1>"""
soup = BeautifulSoup(html, 'html.parser')
Title = soup.find('h1', attrs={'class':'product-name'}).text
print(Title)

输出:

Mixed Brown Rice 2.5kg

关于python - Beautifulsoup .text 函数不返回文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52603355/

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