【问题标题】:Python BeautifulSoup Regex Filter Not WorkingPython BeautifulSoup 正则表达式过滤器不起作用
【发布时间】:2019-10-05 09:59:00
【问题描述】:

我想要 div 类 'hide info-json' 的内容,其父 li 标签类是 'info-wrap' 或 'info-wrap no-meta' 但不是 'info-wrap hide'。

HTML 示例:

<li class="info-wrap">
    <div class="hide info-json">
        <p>Content That I Want - JSON Data </p>
    </div>
</li>

<li class="info-wrap hide">
    <div class="hide info-json">
        <p>Content That I Don't Want </p>
    </div>
</li>

<li class="info-wrap no-meta">
    <div class="hide info-json">
        <p>Content That I Want - JSON Data  </p>
    </div>
</li>

这是我的代码:

soup = BeautifulSoup(res.text, "lxml")        
        for divTags in soup.findAll('li', class_ = re.compile('^(?!.*hide).*info-wrap.*$')):
            for infoList in divTags.find_all('div',{'class':'hide info-json'}):
                Curinfo = json.loads(infoList.text)  

但它什么也不返回。

如果我在https://regex101.com/r/8yJ5yI/1 上检查这个正则表达式,它工作正常。请帮我看看怎么做。

对我来说,使用正则表达式不是必须的,我想要的只是&lt;p&gt;Content That I Want &lt;/p&gt;

谢谢

【问题讨论】:

  • 如果我使用for divTags in soup.findAll(lambda tag: tag.name == 'li' and tag.get('class') == ['info-wrap']):,它会忽略带有info-wrap no-meta类的li标签
  • for divTags in soup.findAll('li'... 仔细阅读,然后再次查看您的 HTML。有道理,它不返回任何匹配项。

标签: python-3.x beautifulsoup findall


【解决方案1】:
import re

html = """<li class="info-wrap">
    <div class="hide info-json">
        <p>Content That I Want - JSON Data </p>
    </div>
</li>

<li class="info-wrap hide">
    <div class="hide info-json">
        <p>Content That I Don't Want </p>
    </div>
</li>

<li class="info-wrap no-meta">
    <div class="hide info-json">
        <p>Content That I Want - JSON Data  </p>
    </div>
</li>"""

l = re.findall(r"""<li\s+class="info-wrap(\s+no-meta)?"\s*>\s*
               <div\s+class="hide\s+info-json"\s*>
               \s*(.*?)\s*
               </div>\s*
               </li>
               """,html, flags=re.VERBOSE|re.IGNORECASE|re.DOTALL)
l = [item[1] for item in l]
print(l)

打印:

['<p>Content That I Want - JSON Data </p>', '<p>Content That I Want - JSON Data  </p>']

See Demo

【解决方案2】:

使用 :not (bs4 4.7.1+) 过滤掉不需要的类

import requests
from bs4 import BeautifulSoup as bs

html = '''<li class="info-wrap">
    <div class="hide info-json">
        <p>Content That I Want - JSON Data </p>
    </div>
</li>

<li class="info-wrap hide">
    <div class="hide info-json">
        <p>Content That I Don't Want </p>
    </div>
</li>

<li class="info-wrap no-meta">
    <div class="hide info-json">
        <p>Content That I Want - JSON Data  </p>
    </div>
</li>'''

soup = bs(html, 'lxml')
print([p.text for p in soup.select('.info-wrap:not(.hide) p')])

【讨论】:

    猜你喜欢
    • 2017-12-27
    • 2017-02-19
    • 2016-03-18
    • 1970-01-01
    • 1970-01-01
    • 2012-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多