【问题标题】:Extracting content of next and different tag using Beautifulsoup使用 Beautifulsoup 提取下一个和不同标签的内容
【发布时间】:2019-12-25 18:12:54
【问题描述】:

我想抓取一些特定的 html 代码。

我的python代码:

    soup = '''

            <p>
                <strong> abc </strong>
            </p>

            <ul>
                <li> 123 </li>
                <li> 456 </li>
            </ul>
    '''

    import bs4
    soup = bs4.BeautifulSoup(soup, 'html.parser')
    for link in soup.find_all('strong') :
        k = link.next_sibling
        print (link.text)
        print (k)
        print (k.text)

和输出:

    abc

    AttributeError: 'NavigableString' object has no attribute 'text'

如何使用上述标签提取“123”和“456”?

谢谢。

【问题讨论】:

    标签: html python-3.x ubuntu beautifulsoup


    【解决方案1】:

    解决方法有很多,比如可以结合find_next()find_next_sibling()方法:

    soup = '''
    
            <p>
                <strong> abc </strong>
            </p>
    
            <ul>
                <li> 123 </li>
                <li> 456 </li>
            </ul>
    '''
    
    import bs4
    soup = bs4.BeautifulSoup(soup, 'html.parser')
    for link in soup.find_all('strong') :
        li1 = link.find_next().li
        li2 = li1.find_next_sibling()
        print(link.text)
        print(li1.text)
        print(li2.text)
    

    打印:

     abc 
     123 
     456 
    

    【讨论】:

      【解决方案2】:

      您想要 123456,因此您可以使用 :has 和 :contains (bs4 4.7.1+) 定位父 p 拥有子 strong 和文本 'abc',然后使用具有类型选择器的相邻兄弟组合器以获取相邻的ul;最后使用带有li 类型选择器的子组合器来获取子li 元素。

      from bs4 import BeautifulSoup as bs
      
      html = '''
      
                  <p>
                      <strong> abc </strong>
                  </p>
      
                  <ul>
                      <li> 123 </li>
                      <li> 456 </li>
                  </ul>
          '''
      
      soup = bs(html, 'lxml')
      print([i.text for i in soup.select('p:has(>strong:contains("abc")) + ul > li')])
      

      阅读 CSS 选择器 here

      【讨论】:

        【解决方案3】:
        from simplified_scrapy.simplified_doc import SimplifiedDoc 
        html = '''<div><p>
                        <strong> abc </strong>
                    </p>
                    <ul>
                        <li> 123 </li>
                        <li> 456 </li>
                    </ul></div>'''
        doc = SimplifiedDoc(html)
        s = doc.strong # doc.getElementByTag('strong')
        lis = s.parent.next.children
        print(s.text) 
        print(lis[0].text) 
        print(lis[1].text) 
        

        结果:

        abc
        123
        456
        

        【讨论】:

          猜你喜欢
          • 2011-08-25
          • 1970-01-01
          • 2021-09-12
          • 1970-01-01
          • 2012-02-13
          • 1970-01-01
          • 2017-03-13
          • 1970-01-01
          • 2020-11-14
          相关资源
          最近更新 更多