使用 beautifulsoup 从网站提取号码?
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(x.strip()) for x in soup.find_all(text=re.compile(r'\b\d+\b'))]
[15660, 435]
以下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(x.strip()) for x in soup.find_all(text=re.compile(r'\b\d+\b'))]
[15660, 435]