栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何使用BeautifulSoup查找评论标签?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何使用BeautifulSoup查找评论标签?

Pyparsing允许您使用内置

htmlComment
表达式搜索HTML注释,并附加解析时回调以验证和提取注释中的各种数据字段:

from pyparsing import makeHTMLTags, oneOf, withAttribute, Word, nums, Group, htmlCommentimport calendar# have pyparsing define tag start/end expressions for the # tags we want to look for inside the commentsspan,spanEnd = makeHTMLTags("span")i,iEnd = makeHTMLTags("i")# only want spans with class=titlefontspan.addParseAction(withAttribute(**{'class':'titlefont'}))# define what specifically we are looking for in this commentweekdayname = oneOf(list(calendar.day_name))integer = Word(nums)dateExpr = Group(weekdayname("day") + integer("daynum"))commentBody = '<!--' + span + i + dateExpr("date") + iEnd# define a parse action to attach to the standard htmlComment expression,# to extract only what we want (or raise a ParseException in case # this is not one of the comments we're looking for)def grabCommentContents(tokens):    return commentBody.parseString(tokens[0])htmlComment.addParseAction(grabCommentContents)# let's try ithtmlsource = """want to match this one<!-- <span > <i>Wednesday 110518</i>(05:00PM)<br /></span> -->don't want the next one, wrong span class<!-- <span > <i>Wednesday 110519</i>(05:00PM)<br /></span> -->not even a span tag!<!-- some other text with a date in italics <i>Wednesday 110520</i>(05:00PM)<br /></span> -->another matching comment, on a different day<!-- <span > <i>Thursday 110521</i>(05:00PM)<br /></span> -->"""for comment in htmlComment.searchString(htmlsource):    parsedDate = comment.date    # date info can be accessed like elements in a list    print parsedDate[0], parsedDate[1]    # because we named the expressions within the dateExpr Group    # we can also get at them by name (this is much more robust, and     # easier to maintain/update later)    print parsedDate.day    print parsedDate.daynum    print

印刷品:

Wednesday 110518Wednesday110518Thursday 110521Thursday110521


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/596408.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号