如何提取和忽略标记中的span? - python

时间:2015-09-22 14:59:03

标签: python html regex beautifulsoup

如何在HTML标记中提取和忽略范围?

我的输入如下:

<ul class="definitions">
<li><span>noun</span> the joining together of businesses which deal with different stages in the production or <a href="sale.html">sale</a> of the same <u slug="product">product</u>, as when a restaurant <a href="chain.html">chain</a> takes over a <a href="wine.html">wine</a> importer</li></ul>

期望的产出:

label = 'noun' # String embedded between <span>...</span>
meaning = 'the joining together of businesses which deal with different stages in the production or sale of the same product, as when a restaurant chain takes over a wine importer' # the text without the string embedded within <span>...</span>
related_to = ['sale', 'chain', 'wine'] # String embedded between <a>...</a>
utag = ['product'] # String embedded between <u>...</u>

我试过这个:

>>> from bs4 import BeautifulSoup
>>> text = '''<ul class="definitions">
...     <li><span>noun</span> the joining together of businesses which deal with different stages in the production or <a href="sale.html">sale</a> of the same <u slug="product">product</u>, as when a restaurant <a href="chain.html">chain</a> takes over a <a href="wine.html">wine</a> importer</li></ul>'''
>>> bsoup = BeautifulSoup(text)
>>> bsoup.text
u'\nnoun the joining together of businesses which deal with different stages in the production or sale of the same product, as when a restaurant chain takes over a wine importer'

# Getting the `label`
>>> label = bsoup.find('span')
>>> label
<span>noun</span>
>>> label = bsoup.find('span').text
>>> label
u'noun'

# Getting the text.
>>> bsoup.text.strip()
u'noun the joining together of businesses which deal with different stages in the production or sale of the same product, as when a restaurant chain takes over a wine importer'
>>> bsoup.text.strip
>>> definition = bsoup.text.strip() 
>>> definition = definition.partition(' ')[2] if definition.split()[0] == label else definition
>>> definition
u'the joining together of businesses which deal with different stages in the production or sale of the same product, as when a restaurant chain takes over a wine importer'

# Getting the related_to and utag
>>> related_to = [r.text for r in bsoup.find_all('a')]
>>> related_to
[u'sale', u'chain', u'wine']
>>> related_to = [r.text for r in bsoup.find_all('u')]
>>> related_to = [r.text for r in bsoup.find_all('a')]
>>> utag = [r.text for r in bsoup.find_all('u')]
>>> related_to
[u'sale', u'chain', u'wine']
>>> utag
[u'product']

使用BeautifulSoup是可以的,但获得所需的东西有点冗长。

还有其他方法可以实现相同的输出吗?

某些群体是否采用正则表达式来捕捉所需的输出?

2 个答案:

答案 0 :(得分:2)

它仍然有一个非常结构良好的结构,你已经清楚地陈述了规则集。我仍然会使用BeautifulSoup应用“提取方法”重构方法来接近它:

from pprint import pprint
from bs4 import BeautifulSoup


data = """
<ul class="definitions">
<li><span>noun</span> the joining together of businesses which deal with different stages in the production or <a href="sale.html">sale</a> of the same <u slug="product">product</u>, as when a restaurant <a href="chain.html">chain</a> takes over a <a href="wine.html">wine</a> importer</li></ul>
"""

def get_info(elm):
    label = elm.find("span")
    return {
        "label": label.text,
        "meaning": "".join(getattr(sibling, "text", sibling) for sibling in label.next_siblings).strip(),
        "related_to": [a.text for a in elm.find_all("a")],
        "utag": [u.text for u in elm.find_all("u")]
    }

soup = BeautifulSoup(data, "html.parser")
pprint(get_info(soup.li))

打印:

{'label': u'noun',
 'meaning': u'the joining together of businesses which deal with different stages in the production or sale of the same product, as when a restaurant chain takes over a wine importer',
 'related_to': [u'sale', u'chain', u'wine'],
 'utag': [u'product']}

答案 1 :(得分:1)

PyQuery是使用BeautifulSoup的另一种选择。它遵循类似jQuery的语法,用于从html中提取信息。

此外,对于正则表达式...可以使用类似下面的内容。

import re

text = """<ul class="definitions"><li><span>noun</span> the joining together of businesses which deal with different stages in the production or <a href="sale.html">sale</a> of the same <u slug="product">product</u>, as when a restaurant <a href="chain.html">chain</a> takes over a <a href="wine.html">wine</a> importer</li></ul>"""

match_pattern = re.compile(r"""
                (?P<label>(?<=<span>)\w+?(?=</span>)) # create the label \
                                                         item for groupdict()
                 """, re.VERBOSE)

match = match_pattern.search(text)
match.groupdict()

输出:

{'label': 'noun'}

使用上面的模板,您也可以在其他html标签的基础上进行构建。它使用(?P<name>...)命名匹配的模式(即标签),然后使用(?=...) 预测断言正向后看断言来执行匹配。

另外,如果您的文档中包含多次提及的文字模式,请查看findallfinditer