【问题标题】:Data Scraping using python And bs4使用 python 和 bs4 进行数据抓取
【发布时间】:2018-05-31 04:43:47
【问题描述】:
<a href="/news/2018/05/israeli-army-projectiles-fired-israel-gaza-180529051139606.html">
    <h2 class="top-sec-title">
        Israel launches counterattacks in Gaza amid soaring tensions
    </h2>
</a>

我想使用 h2 的类,即“top-sec-title”,并用 a 的 href 抓取 h2 上的文本。 下面的示例是我在下面处理的 html 有一个 a 标签类,它帮助我在下面的情况下获得了其子元素中的文本,即 h3

<a class="gs-c-promo-heading gs-o-faux-block-link__overlay-link gel-pica-bold nw-o-link-split__anchor" href="/news/world-us-canada-44294366">
    <h3 class="gs-c-promo-heading__title gel-pica-bold nw-o-link-split__text">
        Hurricane Maria 'killed 4,600 in Puerto Rico'
    </h3>
</a>

下面的代码是我用来从上面的html源中提取数据的。

news = soup.find_all('a', attrs={'class':'gs-c-promo-heading gs-o-faux-block- 
link__overlay-link gel-pica-bold nw-o-link-split__anchor'})

for item in news:
    print(item.get(href))
    print(item.text)

【问题讨论】:

    标签: html python-3.x beautifulsoup


    【解决方案1】:

    这将为您获取包含h2 元素的所有元素,如果封闭元素是a,您将获得href

    lst_of_h2 = soup.find_all('h2', {'class': 'top-sec-title'})
    for h2 in lst_of_h2:
        h2.parent # enclosing element
    

    【讨论】:

    • 请注意,h2 标签没有兄弟姐妹。您可能打算使用.parent
    【解决方案2】:

    代码:

    html = '''
    <a href="/news/2018/05/israeli-army-projectiles-fired-israel-gaza-180529051139606.html">
        <h2 class="top-sec-title">
            Israel launches counterattacks in Gaza amid soaring tensions
        </h2>
    </a>
    '''
    soup = BeautifulSoup(html, 'lxml')
    
    a_tags = [h.parent for h in soup.select('.top-sec-title')]
    
    for a in a_tags:
        print(a['href'])
        print(a.get_text(strip=True))
    

    输出:

    /news/2018/05/israeli-army-projectiles-fired-israel-gaza-180529051139606.html
    Israel launches counterattacks in Gaza amid soaring tensions
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-02-07
      • 2020-09-04
      • 2019-03-12
      • 2018-11-08
      • 2019-02-12
      • 1970-01-01
      • 2013-12-04
      相关资源
      最近更新 更多