【问题标题】:Check if class is equal with one of two strings检查类是否与两个字符串之一相等
【发布时间】:2012-10-15 01:32:22
【问题描述】:

是否可以以某种方式对其进行修改,以便它可以找到类 class1 *OR* 类 class2 的表?

Info = soup.find('table', {'class' :'class1'})

【问题讨论】:

  • 我并没有真正使用过 Beautiful Soup,但也许 this answer 会有所帮助。你能传入一个搜索这两个类的函数吗?

标签: python python-2.7 beautifulsoup


【解决方案1】:
find_all(self, name=None, attrs={}, recursive=True, text=None, limit=None, **kwargs) 

    Extracts a list of Tag objects that match the given
    criteria.  You can specify the name of the Tag and any
    attributes you want the Tag to have.

    The value of a key-value pair in the 'attrs' map can be a
    string, a list of strings, a regular expression object, or a
    callable that takes a string and returns whether or not the
    string matches for some custom definition of 'matches'. The
    same is true of the tag name.

例如:

>>> from bs4 import BeautifulSoup
>>> text = ''.join('<table class="class{}"></table>'.format(i) for i in range(10))
>>> soup = BeautifulSoup(text)
>>> 
>>> soup.find_all("table", {"class": ["class1", "class7"]})
[<table class="class1"></table>, <table class="class7"></table>]
>>> import re
>>> soup.find_all("table", {"class": re.compile("class[17]")})
[<table class="class1"></table>, <table class="class7"></table>]
>>> 
>>> soup.find_all("table", {"class": lambda x: 3*int(x[-1])**2-24*int(x[-1])+17 == -4})
[<table class="class1"></table>, <table class="class7"></table>]

[好吧,最后一个匹配太多了,但你明白了:任何返回布尔值的匹配函数都可以工作。]

【讨论】:

  • 幸好你在第一次尝试时实际上并没有得到最后一个函数,否则我不得不给你+2,这是不可能的。 :)
猜你喜欢
  • 1970-01-01
  • 2015-10-30
  • 2022-06-19
  • 2018-06-07
  • 1970-01-01
  • 1970-01-01
  • 2020-05-05
  • 1970-01-01
相关资源
最近更新 更多