【问题标题】:How can I print the content of each <span> tags that are after every <strong> tag with BeautifulSoup?如何使用 BeautifulSoup 打印每个 <strong> 标签之后的每个 <span> 标签的内容?
【发布时间】:2020-02-25 20:16:49
【问题描述】:

我正在尝试抓取强标记之后的每个跨度标记以及强标记本身的内容。我目前有强标签打印,但似乎无法为每个强标签打印以下跨度标签。这是我的代码:

import bs4 as bs
from urllib.request import urlopen, Request
import urllib


    #all strong tags
    strong_tags = soup.find_all('strong')
    for element in strong_tags:
        element.extract()
        print(element.text)

我得到的输出:

severity:  
ID: 
File Name: 
Version: 
Family: 
Published: 
Dependencies: 
Risk Factor: 
Required KB Items: 

跨度标签的内容应该放在每个冒号之后,但我无法做到。这是我正在抓取的 html 的一部分。

<div class="col-md-4 plugin-single__sidebar">
<h4 class="u-m-t-2">Plugin Details</h4>
<div>
    <p>
        <strong>Severity
            <!-- -->: 
        </strong>
        <span>Critical</span>
    </p>
</div>
<div>
    <p>
        <strong>ID
            <!-- -->: 
        </strong>
        <span>14612</span>
    </p>
</div>
<div>
    <p>
        <strong>File Name
            <!-- -->: 
        </strong>
        <span>aix_IY40501.nasl</span>
    </p>
</div>

【问题讨论】:

    标签: python html web-scraping beautifulsoup


    【解决方案1】:

    试试这个。

    from simplified_scrapy import SimplifiedDoc
    html = '''
    <div class="col-md-4 plugin-single__sidebar">
    <h4 class="u-m-t-2">Plugin Details</h4>
    <div>
        <p>
            <strong>Severity
                <!-- -->: 
            </strong>
            <span>Critical</span>
        </p>
    </div>
    <div>
        <p>
            <strong>ID
                <!-- -->: 
            </strong>
            <span>14612</span>
        </p>
    </div>
    <div>
        <p>
            <strong>File Name
                <!-- -->: 
            </strong>
            <span>aix_IY40501.nasl</span>
        </p>
    </div>
    '''
    doc = SimplifiedDoc(html)
    # First method
    spans = doc.selects('strong>next()')
    print (spans)
    # Second method
    strongs = doc.selects('strong')
    for strong in strongs:
        span = strong.next
        print (strong.text,span.text)
    

    结果:

    [{'tag': 'span', 'html': 'Critical'}, {'tag': 'span', 'html': '14612'}, {'tag': 'span', 'html': 'aix_IY40501.nasl'}]
    Severity : Critical
    ID : 14612
    File Name : aix_IY40501.nasl
    

    【讨论】:

      猜你喜欢
      • 2017-12-02
      • 1970-01-01
      • 1970-01-01
      • 2017-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多