根据Python2.7之前的文本查找数字

2024-05-14 22:39:27 发布

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

如何使用python从以下代码段中提取34980和100329:

<tr id="product_34980" class="even">
<tr id="variant_100329" class="variantRow">

Tags: id代码段producttrclassevenvariantvariantrow
2条回答

使用^{}^{},下面的代码从每一行提取数字。你知道吗

>>> lines = '''<tr id="product_34980" class="even">
... <tr id="variant_100329" class="variantRow">
... '''
>>> [filter(str.isdigit, line) for line in lines.splitlines()]
['34980', '100329']

使用^{}更新

import lxml.html

html_string = '''
<tr id="product_34980" class="even">
<tr id="variant_100329" class="variantRow">
'''

root = lxml.html.fromstring(html_string)
for tr in root.cssselect('tr.even, tr.variantRow'):
    print(tr.get('id')) # => product_34980
    print(tr.get('id').rsplit('_', 1)[-1]) # => 34980

不是最通用的解决方案,但它适用于上面的代码段:

import re

html = """
    <tr id="product_34980" class="even">
    <tr id="variant_100329" class="variantRow">
"""

ids = re.findall(r'id="\w+_(\d+)"', html)

相关问题 更多 >

    热门问题