【问题标题】:How to navigate html using bs4?如何使用 bs4 浏览 html?
【发布时间】:2017-07-01 17:57:28
【问题描述】:

今天下午刚开始学习python。尝试抓取 kubuntu.org(简单 html)的 rss 提要作为练习,但我不知道如何浏览 html 并只打印提要标题:

#!/usr/bin/python3.5
import bs4 as bs
import urllib.request

site = urllib.request.urlopen('https://kubuntu.org/feed').read()
soup = bs.BeautifulSoup(site, 'lxml')

for title in soup.find_all('item'):
    print(title.text)

编辑:

title 添加到find_all 行有点像我想要的,但仍有大量数据也使用标题标签。

#!/usr/bin/python3.5
import bs4 as bs
import urllib.request

site = urllib.request.urlopen('https://kubuntu.org/feed').read()
soup = bs.BeautifulSoup(site, 'lxml')

for title in soup.find_all(['item', 'title']):
    print(title.text)

【问题讨论】:

    标签: python html python-3.x


    【解决方案1】:

    只需访问title标签作为item的子节点:

    ...
    for item in soup.find_all('item'):
        print(item.title.text)
    

    输出:

    Kubuntu Artful Aardvark (17.10) Alpha 1
    Latest round of backports PPA updates include Plasma 5.10.2 for Zesty 17.04
    Plasma 5.10.1 now in Zesty backports
    17.10 Wallpaper Contest deadline for submissions soon
    Plasma bugfix releases, Frameworks, & selected app updates now available in backports PPA for Zesty and Xenial
    17.10 Wallpaper Contest! Call for artists
    KDE PIM update now available for Zesty Zapus 17.04
    KDE PIM update for Zesty available for testers
    Kubuntu 17.04 Released!
    Kubuntu 17.04 Release Candidate – call for testers
    

    【讨论】:

      猜你喜欢
      • 2020-04-13
      • 1970-01-01
      • 2018-12-03
      • 2010-12-09
      • 1970-01-01
      • 2019-08-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多