【问题标题】:Beautiful soup getting all <li> tags after specific <br> tag美丽的汤在特定 <br> 标签之后获得所有 <li> 标签
【发布时间】:2022-01-31 07:48:36
【问题描述】:

我正在尝试获取一个类别下所有产品的所有关键成分,This web page 显示产品成分的列出方式,正如您在下面的页面源截图中看到的那样,所有成分都在 br 标记之后价值“关键成分:” 下面是我的代码,我可以得到所有的文本,但是我怎样才能得到所有的

  • 标签紧跟在“关键成分:”
    标签之后。

    预期输出:

    Glycerin
    Sodium Palmate
    Sodium Palm Kemelate
    Cymbopogon Flexuosus Oil
    Linalool
    Coumarin
    Benzyl Salicylate
    Citral
    

    代码:

    from os.path  import basename
    import requests
    from bs4 import BeautifulSoup
    
    baseurl = "https://www.1mg.com/otc/dettol-original-bathing-soap-bar-125gm-each-buy-4-get-1-free-otc587797"
    
    header = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
                      'Chrome/74.0.3729.169 Safari/537.36 '
    }
    
    r = requests.get(baseurl, headers=header)
    # soup = BeautifulSoup(r, 'lxml')
    soup = BeautifulSoup(r.content, "html.parser")
    job_element = soup.find("div", class_="otc-container")
    categories = job_element.findAll("a", class_="button-text Breadcrumbs__breadcrumb___XuCvk", href=True)
    # print(categories)
    
    description = job_element.find("div", class_="ProductDescription__description-content___A_qCZ")
    print(description.text)
    
    

  • 【问题讨论】:

      标签: python html web-scraping beautifulsoup


      【解决方案1】:

      一种方法是隔离关键成分标记 - 移动到下一个标签 (&lt;br&gt;) - 然后处理所有后续标签,直到到达下一个 &lt;br&gt; 标签。

      <strong>Key Ingredients:</strong>
      <br>
      <ul>
      ...
      ...
      <ul>
      <br>
      
      

      代码:

      >>> for tag in description.find(string='Key Ingredients:').find_next('br').next_elements:
      ...     if tag.name == 'br': break
      ...     if tag.name == 'li': tag.get_text()
      'Glycerin'
      'Sodium Palmate'
      'Sodium Palm Kemelate'
      'Cymbopogon Flexuosus Oil'
      'Linalool'
      'Coumarin'
      'Benzyl Salicylate'
      'Citral'
      

      【讨论】:

      • 太棒了,我不知道我们也可以遍历标签,几周前我开始学习美丽的汤。谢谢
      • the docs 中的各种示例可能会有所帮助。
      猜你喜欢
      • 1970-01-01
      • 2018-07-18
      • 2021-05-03
      • 2014-10-16
      • 2019-11-20
      • 2017-10-19
      • 2019-09-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多