【问题标题】:How can I crawl the specific content in this html with Beautifulsoup?如何使用 Beautifulsoup 抓取此 html 中的特定内容?
【发布时间】:2018-05-21 11:46:51
【问题描述】:

我有一个这样的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。

但是当数字变了,面对其他html时不知道怎么定义一个unified's'。类似的html太多了,我在编码时无法复制每个人。

【问题讨论】:

  • 你可以使用正则表达式来捕获所有的十进制值

标签: python beautifulsoup web-crawler


【解决方案1】:

您可以使用正则表达式来提取浮点值。

例如:

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

【讨论】:

  • 我只是编辑我的问题。当数字改变时,如何定义统一的's'?
  • 我有大约 1000 个类似的 html,只是数量不同。例如,在第二个 html 中,不是 2,1610 而是 3.2302,在第三个中,它是 3.5610。我想使用一个函数并回收它来获取每个 html 中的这些数字。
  • m = re.search("\d+\.\d+", tr.text) 应该适用于所有这些.....正则表达式正在文本中搜索小数
  • 哦,我明白了!
猜你喜欢
  • 2019-08-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多