【问题标题】:Python - Beautiful Soup - Class name exists twicePython - Beautiful Soup - 类名存在两次
【发布时间】:2016-04-11 16:09:01
【问题描述】:

我现在只是在学习如何使用 BS4,但我还没有真正弄清楚的一件事是如何获得一个跨度类,该跨度类位于另一个具有相同名称的跨度类中。

HTML 示例

<span class="test class">
 <span class="another class">
  <span class="test class">
        data I want
  </span>

我一直在为其他数据做的事情是这样的

find('span', class_="test class").get_text().strip()

但是当我想上第二节课时,这需要第一节课。提前致谢。

【问题讨论】:

    标签: python beautifulsoup


    【解决方案1】:

    您需要在具有another class 类的元素内强制执行搜索。您可以通过链接 find() 调用来做到这一点:

    elm = soup.find('span', class_="another class").find('span', class_="test class")
    print(elm.get_text())
    

    或者,一次性使用CSS selector

    elm = soup.select_one("span.another.class > span.test.class")
    print(elm.get_text())
    

    其中&gt; 表示直接的父子关系。

    【讨论】:

      【解决方案2】:

      这对我有用:

      from bs4 import BeautifulSoup
      
      html = """
      <span class="test class">
       <span class="another class">
        <span class="test class">
              data I want
        </span>
      """
      
      soup = BeautifulSoup(html, 'html.parser')
      span = soup.find('span', class_="test class")
      print span.get_text().strip()
      >>> data I want
      

      系统详情:

      • Python 2.7.6
      • beautifulsoup4==4.4.0

      【讨论】:

      • 但是如果 html = """ 数据我不想要 数据我要 """
      【解决方案3】:
      find_all('span', class_="test class")[1].get_text().strip()
      

      这将找到跨度为 class= 'test class' 的所有实例,并将其存储在列表中。然后我们选择列表的第二个元素,它将对应于测试类的第二次出现。

      【讨论】:

      • 你能解释更多吗?
      猜你喜欢
      • 1970-01-01
      • 2018-04-22
      • 2015-11-27
      • 2018-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-15
      • 1970-01-01
      相关资源
      最近更新 更多