如何找到评论标签<!--…——>和美女组在一起?

2024-04-28 21:31:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我试过喝汤。找到('!--’)但似乎没用。提前谢谢。

编辑:谢谢你的提示如何找到所有的评论。我有个后续问题。我该如何特别寻找评论?

例如,我有以下注释标记:

<!-- <span class="titlefont"> <i>Wednesday 110518</i>(05:00PM)<br /></span> -->

我真的只想要这些东西。“110518”是我所依赖的作为搜索目标的年月日。但是,我不知道如何在一个特定的评论标签中找到一些东西。


Tags: 标记br编辑目标评论标签classspan
2条回答

您可以通过findAll方法在文档中找到所有注释。请参见下面的示例,该示例演示如何准确地执行您要执行的操作Removing elements

简而言之,您需要:

comments = soup.findAll(text=lambda text:isinstance(text, Comment))

编辑:如果要在列中搜索,可以尝试:

import re
comments = soup.findAll(text=lambda text:isinstance(text, Comment))
for comment in comments:
  e = re.match(r'<i>([^<]*)</i>', comment.string).group(1)
  print e

Pyparsing允许您使用内置的htmlComment表达式搜索HTML注释,并附加parse time回调来验证和提取注释中的各种数据字段:

from pyparsing import makeHTMLTags, oneOf, withAttribute, Word, nums, Group, htmlComment
import calendar

# have pyparsing define tag start/end expressions for the 
# tags we want to look for inside the comments
span,spanEnd = makeHTMLTags("span")
i,iEnd = makeHTMLTags("i")

# only want spans with class=titlefont
span.addParseAction(withAttribute(**{'class':'titlefont'}))

# define what specifically we are looking for in this comment
weekdayname = 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 it
htmlsource = """
want to match this one
<!-- <span class="titlefont"> <i>Wednesday 110518</i>(05:00PM)<br /></span> -->

don't want the next one, wrong span class
<!-- <span class="bodyfont"> <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 class="titlefont"> <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 110518
Wednesday
110518

Thursday 110521
Thursday
110521

相关问题 更多 >