需要使用RegEx和BeautifulSoup查找文本 [英] Need to find text with RegEx and BeautifulSoup

查看:86
本文介绍了需要使用RegEx和BeautifulSoup查找文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正试图解析一个网站,以提取出一些存储在主体中的数据,例如:

I'm trying to parse a website to pull out some data that is stored in the body such as this:

<body>
    <b>INFORMATION</b>
    Hookups: None
    Group Sites: No
    Station: No

    <b>Details</b>
    Ramp: Yes
</body>

我想使用BeautifulSoup4和RegEx提取连接和组站点等的值,但是我对bs4和RegEx还是陌生的.我已经尝试了以下方法来获取联播网值:

I would like to use BeautifulSoup4 and RegEx to pull out the values for Hookups and Group Sites and so on, but I am new to both bs4 and RegEx. I have tried the following to get the Hookups Value:

soup = BeautifulSoup(open('doc.html'))
hookups = soup.find_all(re.compile("Hookups:(.*)Group"))

但是搜索返回为空.

推荐答案

BeautifulSoup的find_all仅适用于标签.假设HTML如此简单,您实际上可以仅使用纯正则表达式来获得所需的内容.否则,您可以使用find_all,然后获取.text节点.

BeautifulSoup's find_all only works with tags. You can actually use just a pure regex to get what you need assuming the HTML is this simple. Otherwise you can use find_all and then get the .text nodes.

re.findall("Hookups: (.*)", open('doc.html').read())

从BeautifulSoup 4.2开始,您还可以使用text属性按标签内容进行搜索

You can also search by tag content with the text property as of BeautifulSoup 4.2

soup.find_all(text=re.compile("Hookups:(.*)Group"));

这篇关于需要使用RegEx和BeautifulSoup查找文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆