簡體   English   中英

如何從HTML文件中刪除Python中的HTML標簽?

[英]How can I remove HTML tag in Python from HTML file?

摘要:我將使用哪個正則表達式字符串刪除HTML文檔中的標簽? 雖然,這可能是先前答案的重復: 如何僅刪除字符串中的html標簽? 刪除String中的HTML標記 ,我還不能完全用這些語言編程,所以這就是為什么我要問這個問題。

我正在完成Google的Python練習: https : //developers.google.com/edu/python/exercises/baby-names,它需要您兩個使用正則表達式來解析HTML數據(HTML結構化,因此更容易)。 我在刪除數據周圍的標簽時遇到了問題:

   def extract_names(filename):
  """
  Given a file name for baby.html, returns a list starting with the year string
  followed by the name-rank strings in alphabetical order.
  ['2006', 'Aaliyah 91', Aaron 57', 'Abagail 895', ' ...]
  """
  # +++your code here+++
  #open and read file
  file = open(filename,'r')
  HTML = file.read()
  #html file
  #print(HTML)

  #extract date
  date = re.search(r'(Popularity in )([\d]+)',HTML)
  print('Date: ',date.group(2))

  #find rank and name remove html tags
  ranking_tags = re.findall(r'<td>[\d]</td>',HTML)
  rankings = []
  name_tags = re.findall(r'<td>[a-z]</td>',HTML,re.IGNORECASE)
  names = []

  for value in ranking_tags:
      rankings.append(re.sub('[<td></td>]','',value))

  for value in name_tags:
    names.append(re.sub('[<td></td>]','',value))
  print(rankings)
  print(names)

目前,我的正則表達式不會替換標簽,因為它們是錯誤的。 我已經嘗試過教自己如何無濟於事地刪除標簽: http : //www.cbs.dtu.dk/courses/27610/regular-expressions-cheat-sheet-v2.pdfhttps://www.tutorialspoint .com / python / python_reg_expressions.htm以及在撰寫本文之前查看其他景點。

任何建議將不勝感激。

如果不需要regex並且要完成工作,則可以檢查現有的實現。

Django的strip_tags

https://github.com/django/django/blob/master/django/utils/html.py#L183

def _strip_once(value):
    """
    Internal tag stripping utility used by strip_tags.
    """
    s = MLStripper()
    s.feed(value)
    s.close()
    return s.get_data()


@keep_lazy_text
def strip_tags(value):
    """Return the given HTML with all tags stripped."""
    # Note: in typical case this loop executes _strip_once once. Loop condition
    # is redundant, but helps to reduce number of executions of _strip_once.
    value = str(value)
    while '<' in value and '>' in value:
        new_value = _strip_once(value)
        if len(new_value) >= len(value):
            # _strip_once was not able to detect more tags
            break
        value = new_value
    return value

您可以修改該實現。

Python標准庫及其xml模塊

https://docs.python.org/3/library/xml.etree.elementtree.html

它包含有關如何正確使用它的示例。

使用lxml

https://lxml.de/api/lxml.etree-module.html#strip_tags

用法示例:

strip_tags(some_element,
    'simpletagname',             # non-namespaced tag
    '{http://some/ns}tagname',   # namespaced tag
    '{http://some/other/ns}*'    # any tag from a namespace
    Comment                      # comments (including their text!)
    )

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM