2017-03-27 78 views
0

所以我想編程一個可以計算站點上的信息的機器人。我得到了原始的html數據,並檢查該類是否在數據中。但我怎麼能得到之間的數據:Python請求獲取了原始HTML數據,但是如何通過其ID獲取元素中的數據?

<span class="rws"> 10 + 10</span> 

我只需要10 + 10部分。

我不能得到它的工作。我已經試過這樣:

import requests 

from bs4 import BeautifulSoup 

def read(): 
    link = "https://www.matematikfessor.dk/adaptive_test/index/topic:minus-subtraktion--112" 
    f = requests.get(link) 
    htmlData = f.text 
    if('<span class="math" id="MathJax-Span-15" role="math" style="width: 6.362em; display: inline-block;"><span style="display: inline-block; position: relative; width: 5.736em; height: 0px; font-size: 111%;"><span style="position: absolute; clip: rect(1.358em 1005.35em 2.557em -1000.02em); top: -2.187em; left: 0.003em;"><span class="mrow" id="MathJax-Span-16"><span class="mrow" id="MathJax-Span-17"><span class="mn" id="MathJax-Span-18" style="font-family: MathJax_Main;">2,7</span><span class="mo" id="MathJax-Span-19" style="font-family: MathJax_Main; padding-left: 0.263em; padding-right: 0.263em;">-</span><span class="mn" id="MathJax-Span-20" style="font-family: MathJax_Main;">1,57</span><span class="mo" id="MathJax-Span-21" style="font-family: MathJax_Main; padding-left: 0.315em; padding-right: 0.315em;">=</span></span></span><span style="display: inline-block; width: 0px; height: 2.192em;"></span></span></span><span style="display: inline-block; overflow: hidden; vertical-align: -0.286em; border-left: 0px solid; width: 0px; height: 1.102em;"></span></span>' in htmlData): 
     print("Hej") 
    soup = BeautifulSoup(htmlData) 
    quest = soup.find_all("span", class_="math") 
    print(type(quest)) 

def main(): 
    read() 

main() 

回答

0

您可以使用Python BeautifulSoup庫從HTML標籤中提取數據。 這裏是您的解決方案

from bs4 import BeautifulSoup 
    soup = BeautifulSoup('<span class="rws"> 10 + 10</span>') 
    soup.span.string 

這一步後,你會得到字符串10 + 10作爲輸出

+0

但問題是,我永遠也不會知道了「10 + 10」我可能是每一個數字。 – Oscar

+0

如果你想從字符串中提取整數,那麼你可以使用正則表達式或python split方法。 – Sudhakar