我有以下变量,标头等于:
Andrew Anglin
Daily Stormer
February 11, 2017
我只想从此变量中提取日期2017年2月11日.
如何在python中使用BeautifulSoup做到这一点?
解决方法:
如果您知道日期始终是header变量中的最后一个文本节点,则可以访问.contents property并获取返回列表中的最后一个元素:
from bs4 import BeautifulSoup
soup = BeautifulSoup(html, 'html.parser')
header = soup.find('p')
header.contents[-1].strip()
> February 11, 2017
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
但是,正如您的标题所暗示的那样,如果您只想检索未用element标签包裹的文本节点,则可以使用以下内容来过滤掉元素:
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, 2017
标签:python-3-x,beautifulsoup,web-scraping,html,python
来源: https://codeday.me/bug/20191026/1935087.html