【问题标题】:What's the equivalent of '*' for Beautifulsoup - find_all?Beautifulsoup - find_all 的“*”等价物是什么?
【发布时间】:2023-04-05 11:14:01
【问题描述】:

我正在尝试从页面中获取所有 <tr class="**colour blue** attr1 attr2">

attrs 每次都不同,而其他一些兄弟<tr>scolour redcolour pink 等类。

所以我正在寻找classcolour blue 之后的任何其他字符以包含在结果中。我试过使用*,但是没有用:

soup.find_all('tr', {'class': 'colour blue*'})

谢谢

【问题讨论】:

  • 所以,要明确一点,没有什么可以出现在“颜色”之前,但是任何东西都可以跟随“蓝色”?例如,colour bluegray maxsize tall 会匹配,但 altcolour bluegreen 不会匹配?
  • 在这种情况下,可能重复:stackoverflow.com/a/16421470/1085062
  • 我尝试了那里的解决方案,他们只是返回了空列表,出于某种原因

标签: python beautifulsoup


【解决方案1】:

美汤可以用常用的CSS Selectors

>>> soup = BeautifulSoup('''
...     <tr class="colour blue attr1 attr2"></tr>
...     <tr class="colour red attr1 attr2"></tr>
...     <tr class="unwanted attr1 attr2"></tr>
...     <tr class="colour blue attr3"></tr>
...     <tr class="another attr1 attr2"></tr>
... ''')
>>> soup.select('tr.colour.blue')
[<tr class="colour blue attr1 attr2"></tr>, <tr class="colour blue attr3"></tr>]

tr.colours.blue 选择器将匹配 tr,只要它具有 coloursblue 类属性。

【讨论】:

    【解决方案2】:

    使用regex filter:

    import re
    
    soup.find_all('tr', class_=re.compile(r'colour blue.+'))
    
    • 在正则表达式中,它使用re.search() 来查找字符串。

    • . 表示匹配除换行符以外的任何字符。

    • + 表示匹配. 不止一次。

    【讨论】:

    • 现在你有两个问题;)
    猜你喜欢
    • 2011-04-12
    • 1970-01-01
    • 2014-05-08
    • 2014-06-12
    • 1970-01-01
    • 2022-11-28
    • 2012-02-18
    • 1970-01-01
    相关资源
    最近更新 更多