【问题标题】:BeautifulSoup extractBeautifulSoup 提取物
【发布时间】:2012-11-04 05:52:35
【问题描述】:

BeautifulSoup 有一个“问题”,尤其是 re 模块 问题来了:

import re

from bs4 import BeautifulSoup

string = """
<div id="my_id">
    <ul>
        <li>something</li>
        <li class="color12">something</li>
        <li class="color45">something else</li>
    </ul>
</div>
"""
soup = BeautifulSoup(string)
li = soup.find_all('li', {'class': re.compile('color(\d+)')} )
for ele in li:
    print ele['class'] # will print colorXXXX but i would like to know how to get only this XXXX

但我只想提取颜色后的数字。是否有可能或者我有义务使用类似的东西:

match = re.search(r'color(\d+)', str(ele['class']))
if match:
    print match.group(1)

感谢您的帮助:)

【问题讨论】:

    标签: python regex beautifulsoup


    【解决方案1】:

    您必须重新应用正则表达式。只需将其存储在变量中并重复使用:

    colorpattern = re.compile(r'color(\d+)')
    
    li = soup.find_all('li', {'class': colorpattern} )
    for ele in li:
        print colorpattern.search(ele['class']).group(1)
    

    【讨论】:

    • 在这种情况下没关系,但如果正则表达式中有反斜杠,一般使用r''
    • @J.F.Sebastian:我应该在 c&p-ing OP 文本时始终注意这一点。添加。
    • 您能解释一下为什么将编译后的模式存储到变量中会有所不同吗?
    • @Reorx:我们省去了必须两次指定模式的麻烦,而且因为 BS 首先为我们进行了标签匹配,所以我们可以肯定地知道 .search() 将在循环中成功。无需再在那里测试None
    • @MartijnPieters 对不起,我误解了为什么 find_all 只得到一个结果的问题,太愚蠢了!无论如何,谢谢你的回答:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-27
    • 2019-04-15
    • 2021-12-05
    相关资源
    最近更新 更多