【问题标题】:How to print item in a list without a for loop如何在没有for循环的情况下打印列表中的项目
【发布时间】:2021-04-18 18:18:22
【问题描述】:

我试图从网站上获取价格,发现“class="udYkAW2UrhZln2Iv62EYb"”在一行中给了我价格。但是当我尝试打印出来时,我不断得到

<span class="udYkAW2UrhZln2Iv62EYb">$0.312423</span>

而不仅仅是价格本身。我通过使用 for 循环来获取我的项目来解决这个问题,但是有没有办法只使用打印功能而不使用 for 循环来显示价格? 请和谢谢。

这是代码

from bs4 import BeautifulSoup as bs
import requests

url = 'https://robinhood.com/crypto/DOGE'
r = requests.get(url)

#make to soup 
soup = bs(r.content, 'lxml')

#where the price of the search was found "span class='udYkAW2UrhZln2Iv62EYb'"
#Using find() because this is the first instance of this class
price_class = soup.find('span', {'class' : 'udYkAW2UrhZln2Iv62EYb'})
print(price_class)
type(price_class)
    #outout: <span class="udYkAW2UrhZln2Iv62EYb">$0.312423</span>
    #output: bs4.element.Tag

for i in price_class:
    print(i)
        #output: $0.312423

【问题讨论】:

    标签: python-3.x web-scraping beautifulsoup python-requests


    【解决方案1】:

    使用.text.get_text()

    from bs4 import BeautifulSoup as bs
    import requests
    
    url = "https://robinhood.com/crypto/DOGE"
    r = requests.get(url)
    
    soup = bs(r.content, "lxml")
    
    price = soup.find("span", {"class": "udYkAW2UrhZln2Iv62EYb"})
    print(price.text)   # <--- use .text
    

    打印:

    $0.315917
    

    【讨论】:

    • 完美运行!谢谢@AndrejKesly
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-30
    • 1970-01-01
    相关资源
    最近更新 更多