我有以下变量,header等于:
<p>Andrew Anglin<br/>
<strong>Daily Stormer</strong><br/>
February 11, 2017</p>我只想从这个变量中提取日期February 11, 2017。我如何在python中使用BeautifulSoup实现它呢?
发布于 2017-02-11 16:41:36
如果您知道日期始终是标头变量中的最后一个文本节点,那么您可以访问 property并在返回的列表中获取最后一个元素:
from bs4 import BeautifulSoup
soup = BeautifulSoup(html, 'html.parser')
header = soup.find('p')
header.contents[-1].strip()
> February 11, 2017或者,作为MYGz pointed out in the comments below,您可以在新行拆分文本并检索列表中的最后一个元素:
from bs4 import BeautifulSoup
soup = BeautifulSoup(html, 'html.parser')
header = soup.find('p')
header.text.split('\n')[-1]
> February 11, 2017如果您不知道日期文本节点的位置,那么另一个选项是解析任何匹配的字符串:
from bs4 import BeautifulSoup
import re
soup = BeautifulSoup(html, 'html.parser')
header = soup.find('p')
re.findall(r'\w+ \d{1,2}, \d{4}', header.text)[0]
> February 11, 2017但是,正如标题所暗示的那样,如果您只想检索没有用元素标记包装的文本节点,那么您可以使用以下方法过滤掉元素:
from bs4 import BeautifulSoup
import re
soup = BeautifulSoup(html, 'html.parser')
header = soup.find('p')
text_nodes = [e.strip() for e in header if not e.name and e.strip()]请记住,这将返回以下内容,因为第一个文本节点没有包装:
> ['Andrew Anglin', 'February 11, 2017']当然,还可以组合最后两个选项并解析返回文本节点中的日期字符串:
from bs4 import BeautifulSoup
import re
soup = BeautifulSoup(html, 'html.parser')
header = soup.find('p')
for node in header:
if not node.name and node.strip():
match = re.findall(r'^\w+ \d{1,2}, \d{4}$', node.strip())
if match:
print(match[0])
> February 11, 2017https://stackoverflow.com/questions/42178348
复制相似问题