【问题标题】:Python Regex expression for parsing HTML document用于解析 HTML 文档的 Python 正则表达式
【发布时间】:2016-09-23 20:31:48
【问题描述】:

https://en.wikipedia.org/wiki/List_of_largest_companies_by_revenue

我正在尝试按收入顺序查找公司名称。这有点挑战性,因为标题都有不同格式的标签。如果有人能提出解决方案,我将不胜感激。

我的问题的一个例子:

我想匹配“Wal-Mart Stores Inc.”然后是“中石化集团”,依次类推。

<td><a href="/wiki/Wal-Mart_Stores,_Inc." title="Wal-Mart Stores, Inc."class="mw-redirect">Wal-Mart Stores, Inc.</a></td>

...在文档中进一步...

<td style="background: #ffffcc;"><a href="/wiki/Sinopec_Group" title="Sinopec Group" class="mw-redirect">Sinopec Group</a></td>

提前致谢。

【问题讨论】:

  • 首先,您可能不需要正则表达式。其次,看起来他们都是mw-redirect 类的锚点......像BeautifulSoup 这样的东西应该能够根据它来选择项目......
  • 我知道我应该使用BeautifulSoup,尽管我需要使用正则表达式。
  • 为什么不使用原始数据呢?

标签: python html regex


【解决方案1】:

title 属性的内容分组到a 标记中。它检查它是否是排名后的第一个表格单元格。

regex = /th>\n<td.*?><a .* ?title="(.*?)".*>/

已知它目前可以工作。但这是一种相当脆弱的方法。 查看Online Regex Tester 获取正则表达式详细信息

【讨论】:

    【解决方案2】:

    这可以通过beautifulsoup轻松完成

    from bs4 import BeautifulSoup as soup
    
    x = ['<td><a href="/wiki/Wal-Mart_Stores,_Inc." title="Wal-Mart Stores, Inc."class="mw-redirect">Wal-Mart Stores, Inc.</a></td>', '<td style="background: #ffffcc;"><a href="/wiki/Sinopec_Group" title="Sinopec Group" class="mw-redirect">Sinopec Group</a></td>']
    tmp = [soup(y).find('td').find('a') for y in x]
    lst = [x['title'].strip() for x in tmp if x.has_attr('title')]
    print(lst)
    

    如果是单个字符串,则可以使用

    x = '''<td><a href="/wiki/Wal-Mart_Stores,_Inc." title="Wal-Mart Stores, Inc."class="mw-redirect">Wal-Mart Stores, Inc.</a></td> <td style="background: #ffffcc;"><a href="/wiki/Sinopec_Group" title="Sinopec Group" class="mw-redirect">Sinopec Group</a></td>'''
    tmp = [y.find('a') for y in soup(x).find_all('td')]
    lst = [x['title'].strip() for x in tmp if x.has_attr('title')]
    print(lst)
    

    如果你还想使用正则表达式,那么

    <td.*?<a.*? title\s*=\s*"([^"]+).*?</td> 
    

    注意 :- 匹配第一个捕获组

    Regex Demo

    【讨论】:

      猜你喜欢
      • 2010-09-08
      • 2012-09-12
      • 2023-04-02
      • 2014-06-26
      • 1970-01-01
      • 2020-03-14
      • 2014-05-16
      • 2011-06-11
      • 1970-01-01
      相关资源
      最近更新 更多