[英]Extract number from a website using beautifulsoup?
以下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
>>> 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]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.