【问题标题】:Python Beautiful Soup 4 Get Children of Element with .select()Python Beautiful Soup 4 使用 .select() 获取元素的子级
【发布时间】:2017-01-10 05:55:38
【问题描述】:

.select() 元素允许我根据 CSS 选择器从网页中获取一个元素,但这将搜索整个网页。我将如何使用 .select() 但只搜索特定元素的子元素。例如:

<!-- Simplified example of the structure -->
<ul>
    <li>
        <div class="foo">foo content</div>
        <div class="bar">bar content</div>
        <div class="baz">baz content</div>
    </li>
    <li>
        <!-- We can't assume that foo, bar, and baz will always be there -->
        <div class="foo">foo content</div>
        <div class="baz">baz content</div>
    </li>
    <li>
        <div class="foo">foo content</div>
        <div class="bar">bar content</div>
        <div class="baz">baz content</div>
    </li>
</ul>

我想用一种方式说: 对于&lt;li&gt;[0] foo 包含值"foo content",bar 包含值"bar content" 等等。

目前我的解决方案如下:

foos = soup.select("div.foo")
bars = soup.select("div.bar")
bazs = soup.select("div.baz")

for i in range(len(foos)):
    print("{i} contains: {} and {} and {}".format(i=i, foos[i], bars[i], bazs[i]))

这在大多数情况下都有效。但是,当其中一个 li 缺少一个元素时,它就会完全崩溃。就像我在 HTML 中展示的那样,我们不能假设会出现三个 bar、baz 和 foo 元素。

因此,我将如何仅搜索 lis 的子项。因此我可以这样做:

for i in soup.select("li"):
    #how would i do this:
    foo = child_of("li", "div.foo")????
    bar = child_of("li", "div.bar")????
    baz = child_of("li", "div.baz")????

【问题讨论】:

    标签: python css python-3.x beautifulsoup bs4


    【解决方案1】:

    你可以像这样使用element:nth-of-type(n)

    from bs4 import BeautifulSoup
    
    a = """<!-- Simplified example of the structure -->
    <ul>
        <li>
            <div class="foo">foo1 content</div>
            <div class="bar">bar1 content</div>
            <div class="baz">baz1 content</div>
        </li>
        <li>
            <!-- We can't assume that foo, bar, and baz will always be there -->
            <div class="foo">foo2 content</div>
            <div class="baz">baz2 content</div>
        </li>
        <li>
            <div class="foo">foo3 content</div>
            <div class="bar">bar3 content</div>
            <div class="baz">baz3 content</div>
        </li>
    </ul>
    """
    
    s = BeautifulSoup(a)
    s2 = s.select('ul > li:nth-of-type(2)')[0]
    foo, bar, baz = s2.select('div.foo'), s2.select('div.bar'), s2.select('div.baz')
    print foo, bar, baz
    

    输出:

    [<div class="foo">foo2 content</div>] [] [<div class="baz">baz2 content</div>]
    

    【讨论】:

      【解决方案2】:
      for li in soup.select('li'):
          foo = li.select('.foo')
          bar = li.select('.bar')
          baz = li.select('.baz')
      

      每次遍历li标签,使用select(),选择的html代码只有li标签的内容,比如:

      <li>
          <div class="foo">foo content</div>
          <div class="bar">bar content</div>
          <div class="baz">baz content</div>
      </li>
      

      因此,您可以使用select() 来选择 li 的孩子,因为 li 仅包含 child 标记。

      【讨论】:

        【解决方案3】:

        这对我有用,所有的 foos、bars 和 bazs 都存储在单独的列表中

        foos = []
        bars = []
        bazs = []
        for i in soup.find_all('li'):
            soup2 = BeautifulSoup(str(i))
            print soup2
            for _ in soup2.find_all('div', {'class':'foo'}):
                foos.append(_)
            for _ in soup2.find_all('div', {'class': 'bar'}):
                bars.append(_)
            for _ in soup2.find_all('div', {'class': 'baz'}):
                bazs.append(_)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多