【问题标题】:BeautifulSoup finds an html element that contains spaces in its attributesBeautifulSoup 找到一个在其属性中包含空格的 html 元素
【发布时间】:2022-01-16 17:49:19
【问题描述】:

如何使用BeautifulSoup查找属性中包含空格html元素

<h1 class='td p1'>
    title that i want
</h1>
<h1 class='td p2'>
    title that i don't want
</h1>
<h1 class='p1'>
    title that i don't want
</h1>

我想知道如何使用soup.find 来查找title that i want
因为beautifulsoup 认为title 'that i want' 的属性attrs 是这样的:{'class': ['td', 'p1']}.&lt;br&gt;

但不是这样:{'class': ['td p1']}

【问题讨论】:

  • {'class': ['td', 'p1']}{'class': ['td p1']} 都有效。你到底有什么问题?
  • 如何使用soup.find找到&lt;h1 class = 'td p1'&gt; title that i want &lt;/h1&gt;
  • 因为当我做 soup.find_all (class= 'td') 时。 Beautifusoup 发现:&lt;h1 class = 'td p1'&gt; title that i want &lt;/h1&gt; &lt;h1 class = 'td p2'&gt; title that i don't want &lt;/h1&gt; 当我执行 soup.find_all (class= 'p1') 时。 Beautifusoup 发现:&lt;h1 class = 'td p1'&gt; title that i want &lt;/h1&gt; &lt;h1 class = 'p1'&gt; title that i don't want &lt;/h1&gt;
  • 请看下面的答案。是你要找的吗?
  • 我放了一个更通用的案例。但我的印象是,就我个人而言,它是有效的。我不知道我们可以放置空格。所以是的,它有效。也许我的问题来自其他地方。所以我将关闭问题

标签: python web-scraping beautifulsoup


【解决方案1】:

注意 不同的方法,但都有共同点来明确选择类。

查找()
soup.find('h1', attrs={'class':'td p1'})
select_one()
soup.select_one('h1.td.p1')

示例

from bs4 import BeautifulSoup
data="""
<h1 class='td p1'>
    title that i want
</h1>
<h1 class='td p2'>
    title that i don't want
</h1>
<h1 class='p1'>
    title that i don't want
</h1>
"""
soup=BeautifulSoup(data,"html.parser")

title = soup.select_one('h1.td.p1')

print(title)

输出

<h1 class="td p1">
    title that i want
</h1>

【讨论】:

    【解决方案2】:
    html = """<h1 class='td p1'>
        title that i want
    </h1>
    <h1 class='td p2'>
        title that i don't want
    </h1>
    <h1 class='p2'>
        title that i don't want
    </h1>"""
    
    soup = BeautifulSoup(html, "lxml")
    content = soup.find('h1', attrs={'class':'td p1'})
    

    输出:

    >>> print(content)
    <h1 class="td p1">
        title that i want
    </h1>
    

    【讨论】:

      猜你喜欢
      • 2011-09-24
      • 1970-01-01
      • 1970-01-01
      • 2017-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-23
      • 2015-03-30
      相关资源
      最近更新 更多