简体   繁体   English

BeautifulSoup获得一定价值

[英]BeautifulSoup get a certain value

I'm using a really simple thing to get the information I need: 我正在使用一个非常简单的方法来获取所需的信息:

a = soup.find_all(class_ = "pull-right hidden-phone")
print(a)
print(a[0])

And the output is: 输出为:

[<span class="pull-right hidden-phone"><span data-c="190000000" data-time="1535345254000">1.9 BTC</span></span>, <span class="pull-right hidden-phone"><span data-c="4890548" data-time="1535345254000">0.04890548 BTC</span></span>]
<span class="pull-right hidden-phone"><span data-c="190000000" data-time="1535345254000">1.9 BTC</span></span>

I want to get 1.9 BTC or 190000000 but don't know how to. 我想获得1.9 BTC或190000000,但不知道如何获得。 I've tried print(a[0]["data-time"]) and that doesn't work, it says 我已经尝试过print(a[0]["data-time"]) ,但它不起作用,它说

return self.attrs[key] KeyError: 'data-time' 返回self.attrs [key] KeyError:“数据时间”

However, this print(a[0]["class"]) works and gives the ['pull-right', 'hidden-phone'] as a result. 但是,此print(a[0]["class"])可以工作,并因此得到['pull-right', 'hidden-phone']

So how can I get a 1.9 BTC or 190000000? 那么我如何获得1.9 BTC或190000000?

Use print(a.find("span").span["data-time"]) or print(a.span.span["data-time"]) 使用print(a.find("span").span["data-time"])print(a.span.span["data-time"])

Ex: 例如:

from bs4 import BeautifulSoup
s = """<span class="pull-right hidden-phone"><span data-c="190000000" data-time="1535345254000">1.9 BTC</span></span>"""
a = BeautifulSoup(s, "html.parser")

print(a.find("span").span["data-time"])
print(a.span.span["data-c"])
print(a.span.span.text)

Output: 输出:

1535345254000
190000000
1.9 BTC

You should try this way, May this help 您应该尝试这种方式,希望对您有所帮助

from bs4 import BeautifulSoup
text = """
<span class="pull-right hidden-phone"><span data-c="190000000" data-time="1535345254000">1.9 BTC</span></span>, 
<span class="pull-right hidden-phone"><span data-c="4890548" data-time="1535345254000">0.04890548 BTC</span></span>
"""

soup = BeautifulSoup(text, 'html.parser')
for tag in soup.find_all('span', attrs={'class': 'pull-right hidden-phone'}):
    span_tag = tag.span
    print('Attribute Value:', span_tag.get('data-c'), 'Date-time:', span_tag.get('data-time'), 'Tag Text:', span_tag.get_text())


# Output as: 
# Attribute Value: 190000000 Date-time: 1535345254000 Tag Text: 1.9 BTC
# Attribute Value: 4890548 Date-time: 1535345254000 Tag Text: 0.04890548 BTC

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM