gofeed强大的提要解析器

联合创作 · 2023-09-23 13:42

gofeed库是一个强大的提要(feed)解析器,支持解析 RSSAtom 和 JSON 提要。该库提供了一个通用模型gofeed.Parser,它可以解析所有提要类型,并将其转换为混合gofeed.Feed模型。


gofeed库由一个通用提要解析器 gofeed. Parser和几个特定类型解析器(rss.Parser 、atom.Parserjson. Parser


如果要同时处理 rss、atom 和 json 提要,那么使用gofeed. Parser,如果只解析一种提要类型,就使用对应的解析器。


 



gofeed会尽最大努力解析损坏的和无效的 XML 提要。目前,gofeed可以成功解析具有以下问题的提要:



  • 提要元素中的未转义/裸标记

  • 未声明的命名空间前缀

  • 某些元素上缺少结束标记

  • 没有命名空间前缀的提要元素中的非法标签

  • 缺少相应提要规范指定的“必需”元素。

  • 日期格式不正确


支持的提要类型



  • RSS 0.90

  • Netscape RSS 0.91

  • Userland RSS 0.91

  • RSS 0.92

  • RSS 0.93

  • RSS 0.94

  • RSS 1.0

  • RSS 2.0

  • Atom 0.3

  • Atom 1.0

  • JSON 1.0

  • JSON 1.1


基本用法


通用源解析器


最常见的使用场景是用于gofeed.Parser将任意 RSS 或 Atom 或 JSON 提要解析到混合gofeed.Feed模型中。这种混合模型允许您以相同的方式处理 RSS、Atom 和 JSON 提要。


从 URL 解析提要:



fp  :=  gofeed。NewParser ()
feed , _ := fp。ParseURL ( "http://feeds.twit.tv/twit.xml" )
fmt。Println ( feed . Title )


从字符串解析提要:



feedData  :=  `<rss version="2.0"> 
<channel>
<title>Sample Feed</title>
</channel>
</rss>`
fp := gofeed。NewParser ()
feed , _ := fp。ParseString ( feedData )
fmt。Println ( feed . Title )

从  io. Reader 解析:


file, _ := os.Open("/path/to/a/file.xml")
defer file.Close()
fp := gofeed.NewParser()
feed, _ := fp.Parse(file)
fmt.Println(feed.Title)

解析一个超时 60 秒的URL:


ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
defer cancel()
fp := gofeed.NewParser()
feed, _ := fp.ParseURLWithContext("http://feeds.twit.tv/twit.xml", ctx)
fmt.Println(feed.Title)

使用自定义的 User-Agent 从 URL 解析提要:


fp := gofeed.NewParser()
fp.UserAgent = "MyCustomAgent 1.0"
feed, _ := fp.ParseURL("http://feeds.twit.tv/twit.xml")
fmt.Println(feed.Title)

浏览 31
点赞
评论
收藏
分享

手机扫一扫分享

编辑 分享
举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

编辑 分享
举报