在Python中使用REGEX匹配行之间的元素

2024-04-26 20:37:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在寻找使用正则表达式提取购物网站的数量。在下面的例子中,我想得到“12.5公斤”。但是,第一个跨度内的数量并不总是以千克为单位;可以是磅、盎司等

        <td class="size-price last first" colspan="4">
                    <span>12.5 kilograms </span>
            <span> <span class="strike">$619.06</span> <span class="price">$523.91</span>
                    </span>
                </td>

上面的代码只是使用BeautifulSoup实际提取的代码的一小部分。无论是哪一页,数量总是在一个范围内,并且在一个新的行之后

<td class="size-price last first" colspan="4">  

我过去用过正则表达式,但我远不是专家。我想知道如何在不同的行之间匹配元素。在这种情况下

<td class="size-price last first" colspan="4">

以及

<span> <span class="strike">

Tags: 代码size数量网站购物priceclass例子
1条回答
网友
1楼 · 发布于 2024-04-26 20:37:20

Avoid用regex解析HTML。使用这个工具,一个HTML解析器,比如BeautifulSoup——它功能强大,易于使用,可以完美地处理您的案例:

from bs4 import BeautifulSoup


data = """
<td class="size-price last first" colspan="4">
                    <span>12.5 kilograms </span>
            <span> <span class="strike">$619.06</span> <span class="price">$523.91</span>
                    </span>
                </td>"""
soup = BeautifulSoup(data)

print soup.td.span.text

印刷品:

12.5 kilograms 

或者,如果td是更大结构的一部分,则按类查找它并从中获取第一个span的文本:

print soup.find('td', {'class': 'size-price'}).span.text

UPD(处理多个结果):

print [td.span.text for td in soup.find_all('td', {'class': 'size-price'})]

希望有帮助。你知道吗

相关问题 更多 >