【问题标题】:Beautifulsoup .text function returns no textBeautifulsoup .text 函数不返回文本
【发布时间】:2019-03-07 06:51:58
【问题描述】:

我试图提取运行代码返回的 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 标签中取出文本?

【问题讨论】:

    标签: python html beautifulsoup


    【解决方案1】:

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

    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
    

    【讨论】:

    • 刚刚做了。你知道为什么价格没有被提取吗?
    • 好的,我正在检查。
    • 设法让它现在工作。使用class_=attrs 有什么区别?
    • 不客气 :)
    猜你喜欢
    • 2020-02-28
    • 2012-08-20
    • 2013-04-29
    • 2016-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-22
    • 2013-05-30
    相关资源
    最近更新 更多