以下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从网站中提取数字。但我不知道怎么做?
呼叫 soup.find_all ,带有正则表达式-
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
>>> [int(x.strip()) for x in soup.find_all(text=re.compile(r'\b\d+\b'))] [15660, 435]