python-BeautifulSoup:提取不在给定标签中的文本
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python-BeautifulSoup:提取不在给定标签中的文本,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1625字,纯文字阅读大概需要3分钟。
内容图文
![python-BeautifulSoup:提取不在给定标签中的文本](/upload/InfoBanner/zyjiaocheng/684/0af537ef5c5543b989074e7161dd5e16.jpg)
我有以下变量,标头等于:
<p>Andrew Anglin<br/>
<strong>Daily Stormer</strong><br/>
February 11, 2017</p>
我只想从此变量中提取日期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
或者,作为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
但是,正如您的标题所暗示的那样,如果您只想检索未用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-BeautifulSoup:提取不在给定标签中的文本全部内容,希望文章能够帮你解决python-BeautifulSoup:提取不在给定标签中的文本所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。