如何使用Beautifulsoup抓取此HTML中的特定内容?

时间:2018-05-21 11:46:51

标签: python beautifulsoup web-crawler

我有一个像这样的HTML:

<tr>
<td>
<b>
<a href=".././statistics/power" title="Exponent of the power-law degree distribution">Power law exponent (estimated) with d<sub>min</sub></a>
</b>
</td>
<td>2.1310 (d<sub>min</sub> = 49) 
</td>
</tr>

此外,我有许多其他html几乎与此相同,但在底部的第三行中有不同的数字。 我想在这个HTML中抓取这些数字,如2.1310,但不知道该怎么做。

这是我的代码:

def getLinks(Url):
    html=urlopen(Url)
    s = '<tr><td><b><a href=".././statistics/power" title' \
    '="Exponent of the power-law degree distibution">Power law exponent (estimated) with ' \
    'd<sub>min</sub></a></b></td><td>2.1310(d<sub>min</sub> = 49) </td></tr>'
    soup = BeautifulSoup(s, 'html.parser')
    print(soup.find_all('td')[1].contents[0][:-2])

我可以使用此代码获得2.1310。

但是当数字发生变化时,我不知道如何定义统一&#39;&#39;当面对其他HTML时。有很多类似的htmls,我无法在编码时复制每个人。

1 个答案:

答案 0 :(得分:1)

您可以使用Regex提取Float值。

<强>实施例

from bs4 import BeautifulSoup
import re
s = '<tr><td><b><a href=".././statistics/power" title' \
    '="Exponent of the power-law degree distibution">Power law exponent (estimated) with ' \
    'd<sub>min</sub></a></b></td><td>2.1610(d<sub>min</sub> = 2) </td></tr>'
soup = BeautifulSoup(s, 'html.parser')
for tr in soup.find_all('tr'):
    m = re.search("\d+\.\d+", tr.text)
    if m:
        print(m.group())

<强>输出:

2.1610