0

I want to extract just the inner text 24,000.00 from the following tag:

<span class="itm-price mrs  ">
     <span data-currency-iso="BDT">৳&lt;/span> 
     <span dir="ltr" data-price="24000">24,000.00</span> 
</span>

There are many similar tag like this in the page from where I want to extract data.

I'm trying to do this:

    for price in soup.find_all('span', {'class': 'itm-price'}):
        item_price = price.get('data-price')
        print(item_price)

But Output is coming : None

I learned from the Bs4 doc that for html5 data-* tag we should use :

data_soup.find_all(attrs={"data-foo": "value"})
# [<div data-foo="value">foo!</div>]

As I'm very newbie here so I'm still unable to bring resutls using the method.

4

3 回答 3

2

你可以试试这个

>>> import re
>>> from bs4 import BeautifulSoup
>>> html_doc = """
... <span class="itm-price mrs  ">
...      <span data-currency-iso="BDT">৳&lt;/span> 
...      <span dir="ltr" data-price="24000">24,000.00</span> 
... </span>
... <span class="itm-price mrs  ">
...      <span data-currency-iso="BDT">৳&lt;/span> 
...      <span dir="ltr" data-price="25000">25,000.00</span> 
... </span>
... <span class="itm-price mrs  ">
...     <span data-currency-iso="BDT">৳&lt;/span> 
...     <span dir="ltr" data-price="blabla">blabla</span> 
... </span>
... """
>>> soup = BeautifulSoup(html_doc, 'html.parser')
>>> soup.find("span", dir="ltr").attrs['data-price']

# You can loop over

>>> for price_span in soup.find_all("span", attrs={"dir": "ltr", "data-price": re.compile(r"\d+")}):
...     print(price_span.attrs.get("data-price", None))

# output
24000
25000
于 2015-09-02T18:23:48.527 回答
2

<span>当您可以直接访问您想要的那些时,为什么还要寻找周围的环境?此外,您可以使用关键字参数(尽管我理解为什么您不想尝试使用该class属性,因为它是 Python 关键字)。

get_test()方法将从一对匹配的标签之间提取内容,因此您最终会得到一个非常简单的程序:

# coding=utf-8
data = u"""\
<span class="itm-price mrs  ">
     <span data-currency-iso="BDT">৳&lt;/span>
     <span dir="ltr" data-price="24000">24,000.00</span>
</span>
"""

import bs4
soup = bs4.BeautifulSoup(data)
for price in soup.find_all('span', dir="ltr"):
    print(price.get_text())
于 2015-09-02T19:11:30.270 回答
0

使用查找方法:

>>>from bs4 import BeautifulSoup
>>>url="""<span class="itm-price mrs  "><span data-currency-iso="BDT">৳&lt;/span><span dir="ltr" data-price="24000">24,000.00</span></span>"""
>>>soup.find("span",dir="ltr").string
'24,000.00'
于 2015-09-02T18:05:23.103 回答