【问题标题】:Python - Web Scraping :How to access div tag of 1 class when I am getting data for div tags for multiple classesPython - Web Scraping:当我获取多个类的 div 标签的数据时,如何访问 1 个类的 div 标签
【发布时间】:2020-06-04 16:11:21
【问题描述】:

我希望结果中有 2 个不同类的 div 标签。 我正在使用以下命令 scrape 数据 - '''

result = soup.select('div', {'class' : ['col-s-12', 'search-page-text clearfix row'] })

'''

现在,我在“col-s-12”类中有一组特定的信息,而在“search-page-text clearfix row”类中有另一组信息 现在,我想找到只有 div 标签的子类 - 'col-s-12'。当我在代码下方运行时,它会查找两个 div 标记的子级,因为我没有在任何地方指定要搜索的类

'''

for div in result:
    
     
    print(div)
    prod_name = div.find("a" , recursive=False)[0]    #should come from 'col-s-12' only
    prod_info  = div.find("a" , recursive=False)[0]   # should come from 'search-page-text clearfix row' only

'''

示例 - '''

<div class = 'col-s-12'>
       <a href = "some_link"> This is what I want or variable **prod_name** </a>
</div>
<div class = 'search-page-text clearfix row'> 
       <a>   This should be stored in variable **prod_info**     </a>
</div>

'''

【问题讨论】:

    标签: python-3.x web-scraping beautifulsoup


    【解决方案1】:

    您可以在class="col-s-12"标签下搜索第一个&lt;a&gt;标签,然后使用.find_next('a')搜索下一个&lt;a&gt;标签。

    注意:.select() 方法只接受 CSS 选择器,不接受字典。

    例如:

    txt = '''<div class = 'col-s-12'>
           <a href = "some_link"> This is what I want or variable **prod_name** </a>
    </div>
    <div class = 'search-page-text clearfix row'>
           <a>   This should be stored in variable **prod_info**     </a>
    </div>'''
    
    from bs4 import BeautifulSoup
    
    
    soup = BeautifulSoup(txt, 'html.parser')
    
    prod_name = soup.select_one('.col-s-12 > a')
    prod_info = prod_name.find_next('a')
    
    print(prod_name.get_text(strip=True))
    print(prod_info.get_text(strip=True))
    

    打印:

    This is what I want or variable **prod_name**
    This should be stored in variable **prod_info**
    

    【讨论】:

      猜你喜欢
      • 2021-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多