2017-03-27 43 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