【问题标题】:Finding multiple attributes within the span tag in Python在 Python 中的 span 标签内查找多个属性
【发布时间】:2015-07-04 20:08:09
【问题描述】:

我希望从网站上抓取两个值。这些存在于以下标签中:

<span class="sp starBig">4.1</span>
<span class="sp starGryB">2.9</span>

我需要值 sp starBig、sp starGryB。

我使用的 findAll 表达式是 -

soup.findAll('span', {'class': ['sp starGryB', 'sp starBig']}):

代码执行没有任何错误,但没有显示结果。

【问题讨论】:

  • 您使用的是哪个版本的 BeautifulSoup?
  • 最后有个':'..
  • 你需要 of sp starBig 和 sp starGryB 的值吗?
  • @skyline75489 抱歉。我不确定它是哪个版本。我怎么知道?我是新手。
  • 你是导入 bs4 还是 BeautifulSoup?

标签: python beautifulsoup


【解决方案1】:

根据docs,假设Beautiful Soup 4,使用'sp starGryB' 之类的字符串匹配多个CSS 类是脆弱的,不应该这样做:

soup.find_all('span', {'class': 'sp starGryB'})
# [<span class="sp starGryB">2.9</span>]
soup.find_all('span', {'class': 'starGryB sp'})
# []

应该使用CSS selectors,如下所示:

soup.select('span.sp.starGryB')
# [<span class="sp starGryB">2.9</span>]
soup.select('span.starGryB.sp')
# [<span class="sp starGryB">2.9</span>]

在你的情况下:

items = soup.select('span.sp.starGryB') + soup.select('span.sp.starBig')

或更复杂的东西,例如:

items = [i for s in ['span.sp.starGryB', 'span.sp.starBig'] for i in soup.select(s)]

【讨论】:

  • items = [i for s in ['span.sp.starGryB', 'span.sp.starBig'] for i in soup.select(s): try: print(i.string)除了 KeyError:通过
  • items = soup.select('span.sp.starGryB') + soup.select('span.sp.starBig') 正在工作。
  • @Dixon 第二个选项只是使用list comprehension,其中包括[] 的表达式,而不是标准的for 循环。删除了行拆分以希望提高清晰度。
【解决方案2】:

可能有更好的方法,但目前我还没有找到。可以使用这样的 css 选择器来完成:

html = '''<span class="sp starBig">4.1</span>
          <span class="sp starGryB">2.9</span>
          <span class="sp starBig">22</span>'''

soup = bs4.BeautifulSoup(html)

selectors = ['span.sp.starBig', 'span.sp.starGryB']
result = []
for s in selectors:
    result.extend(soup.select(s))

【讨论】:

    【解决方案3】:

    soup.findAll('span', {'class': ['sp starGryB', 'sp starBig']}) 这段代码很有帮助,对我很有帮助

    【讨论】:

    • 您好,这与问题中的代码有何不同?
    • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
    猜你喜欢
    • 2019-09-03
    • 2017-03-13
    • 2011-08-08
    • 2011-12-02
    • 1970-01-01
    • 2018-07-06
    • 1970-01-01
    • 2014-04-13
    • 1970-01-01
    相关资源
    最近更新 更多