使用beautifulsoup从网站中提取数字?

时间:2018-01-10 04:46:15

标签: python beautifulsoup extract

以下python代码:

from bs4 import BeautifulSoup
div = '<div class="hm"><span class="xg1">查看:</span> 15660<span class="pipe">|</span><span class="xg1">回复:</span> 435</div>'
soup = BeautifulSoup(div, "lxml")
hm = soup.find("div", {"class": "hm"})
print(hm)

在这种情况下我需要两个数字的输出:

15660
435

我想尝试使用beautifulsoup从网站中提取数字。但我不知道怎么做?

1 个答案:

答案 0 :(得分:0)

使用正则表达式调用soup.find_all -

>>> list(map(str.strip, soup.find_all(text=re.compile(r'\b\d+\b'))))

或者,

>>> [x.strip() for x in soup.find_all(text=re.compile(r'\b\d+\b'))]

['15660', '435']

如果您需要整数而不是字符串,请在列表解析中调用int -

>>> [int(x.strip()) for x in soup.find_all(text=re.compile(r'\b\d+\b'))]
[15660, 435]