簡體   English   中英

Python BS4沒有在find_all()函數中返回Unicode值

[英]Python BS4 not returning a Unicode value in find_all() function

對於一個學校項目,我想編寫一個python程序,從這個網站中提取比特幣的當前價值: http//www.coindesk.com/price/ 為此,我安裝了BeautifulSoup4和Requests庫,以便提取HTML數據並解析它,但是當實際獲得價格的時候,我的程序什么都不返回。 這里是一個圖片的什么,我試圖讓。 這是我的代碼:

import requests as r
from bs4 import BeautifulSoup as bs
doc = r.get("http://www.coindesk.com/price/")
soup = bs(doc.content, "html.parser")
price = soup.find_all("a", {"class":"bpiUSD"})
text = []
contents = []
for item in price:
    text.append(item.text)
for item in price:
    contents.append(item.contents)
print "text:", type(text[0])
print "contents:", type(contents[0])
print "text[0]:", text[0]
print "contents[0]", contents[0]

這是輸出:

text: <type 'unicode'>
contents: <type 'list'>
text[0]: 
contents[0] []

我用這種方式來獲取字符串和數字並且它起作用但是當它達到這個特定數字時它沒有返回任何東西。 此外,我知道比特幣的價格是用Unicode(至少我假設這個),我試圖將其轉換為字符串值,但是盡管.type()函數確實提到列表是Unicode,但沒有任何效果。

您將要么必須找到不同的網站或使用selenium webdriver。 價格是由請求不執行的javascript生成的。

from bs4 import BeautifulSoup as bs

doc = r.get("http://www.coindesk.com/price/")
soup = bs(doc.content, "lxml")
price = soup.find_all(class_="currency-price")
print(price)

打印:

[<div class="currency-price">
<a class="bpiUSD" href="/price/" style="color:white;"></a>
</div>, <div class="currency-price">
<a class="bpiUSD" href="/price/" style="color:white;"></a>
</div>]

哪個不包含您的號碼。 如果您檢查網站上的html,它將具有a標簽之間的數字。 使用像selenium這樣的庫可以讓你運行javascript。

您嘗試使用Beautiful soup解析的網站正在通過javascript調用呈現,這些調用正在從數據的api發布json中獲取數據,即coindesk api 這就是你美麗的湯調用不起作用的原因。

要獲取此數據,您需要使用請求請求json,然后迭代到您需要的數據。

我在下面的腳本中為您完成了該過程。 我添加了注釋,以便您了解我在每個部分中所做的工作。 它可以用更少的代碼行完成,但我認為這有助於你更好地理解如何遍歷json。

這是在python 3中,如果你想在python2.7中輸出更漂亮,刪除print語句周圍的括號。

import requests
jsonurl = 'http://api2.coindesk.com/site/headerdata.json?currency=BTC'
json = requests.get(jsonurl).json()

for key, value in json.items():                     #Loop through the first branch of the json
    if type(value) == type(dict()):                 #each branch that has a dictionary is what contains the currency and rate
        for subKey, subValue in value.items():      #Loop through those dictionaries
            if type(subValue) == type(dict()):      #if there is a dictionary in this key value pair then we loop through them.
                for subKey1, subValue1 in subValue.items():     #Our final loop
                    if subKey1 == 'rate_float':                 #The rates are held in rate_float value in this key
                        print('exchange: ' + subKey, 'rate: ' +  str(subValue1)             )

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM