【问题标题】:Retrieving string between whitespace检索空格之间的字符串
【发布时间】:2014-08-21 15:38:11
【问题描述】:

我有一个属于变量 tbody 的字符串,如下所示:

tbody = 
'...
</td>
<td class="Details clearfix">
<div>
<b>

9. I want this text and number

            </b>
</div>
</td>
<td class="flux">
...'

>print type(tbody)
<type 'str'>

正如您可能已经看到的那样,有空格。 我试图检索'9。我想要这个文本和数字'使用以下代码:

tbody2 = str(tbody.split(','))
tbody2 = str(re.split('\n|\r|\t', tbody2))
m = re.findall(re.compile("\\\\n(.+?)\\\\"), tbody2)
print m

这是我得到的结果:

[...'<td class="Details clearfix">', '<div>', '<b>',
'\\', '9. I want this text and number', '\\', '                </b>', '</div>',
'</td>', '<td class="flux>'...]

我无法获取字符串,所以有没有办法使用 BS 或正则表达式来检索它?干杯

【问题讨论】:

    标签: python regex beautifulsoup whitespace


    【解决方案1】:
    from bs4 import BeautifulSoup
    
    tbody = """
    <td class="Details clearfix">
    <div>
    <b>
    
    9. I want this text and number
    
                </b>
    </div>
    </td>
    
    """
    soup = BeautifulSoup(tbody)
    for item in soup.find_all('td',class_="Details clearfix"):
        print item.div.b.text.strip()
    
    #output= 9. I want this text and number
    

    我认为没有必要通过在美丽的汤中搜索来获取预期的输出

    【讨论】:

      【解决方案2】:

      你可以通过 Python 的 re 模块使用 DOTALL 修饰符来做到这一点,

      >>> import re
      >>> m = re.search(r'<td.*?>.*?<b>\s*([^\n]*).*<\/b>.*?<\/td>', tbody, re.DOTALL)
      >>> m.group(1)
      '9. I want this text and number'
      

      DEMO

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-02-07
        • 2013-01-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-09-23
        • 1970-01-01
        相关资源
        最近更新 更多