【问题标题】:Does BeautifulSoup support custom html tags?BeautifulSoup 是否支持自定义 html 标签?
【发布时间】:2020-03-28 09:19:36
【问题描述】:

我正在尝试构建一个 youtube-playlist-downloader,其中包括使用 BeautifulSoup 抓取播放列表的网页以获取视频的 href。在检查了一个youtube播放列表网页后,我发现视频信息是ytd-playlist-video-renderer标签的孩子。所以,我尝试运行以下 python 脚本

    html = urllib.request.urlopen(url).read()
    soup = BeautifulSoup(html, "html.parser")

    hrefs = list()
    tags = soup('ytd-playlist-video-renderer')
    count = len(tags)
    print(count)

我希望它打印播放列表中的视频数量,但每次都打印 0。有办法吗?

【问题讨论】:

    标签: python beautifulsoup download youtube html-parser


    【解决方案1】:

    可以,但您应该使用find 方法之一。

    from bs4 import BeautifulSoup
    
    soup = BeautifulSoup('<custom_tag>text</custom_tag>', 'html.parser')
    
    print(soup.findAll('custom_tag'))
    print(len(soup.findAll('custom_tag')))
    

    输出

    [<custom_tag>text</custom_tag>]
    1
    

    【讨论】:

      【解决方案2】:

      试试这个。

      from simplified_scrapy.simplified_doc import SimplifiedDoc 
      doc = SimplifiedDoc(html)
      # If ytd-playlist-panel-video-renderer is a tag, use this
      lst = doc.getElementsByTag('ytd-playlist-panel-video-renderer')
      print (lst)
      # If ytd-playlist-panel-video-renderer is a class, use this
      lst = doc.getElementsByClass('ytd-playlist-panel-video-renderer')
      print (lst)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-10-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多