【问题标题】:Extract html data using regular expressions使用正则表达式提取html数据
【发布时间】:2015-02-24 05:21:26
【问题描述】:

我有一个看起来像这样的 html 页面

<tr>
    <td align=left>
        <a href="history/2c0b65635b3ac68a4d53b89521216d26.html">
            <img src="/images/page.gif" border="0" title="полная информация о документе" width=20 height=20>
        </a> 
        <a href="history/2c0b65635b3ac68a4d53b89521216d26_0.html" title="C.">Th</a>
    </td>
</tr>
<tr align=right>
    <td align=left>
        <a href="marketing/3c0a65635b2bc68b5c43b88421306c37.html">
            <img src="/images/page.gif" border="0" title="полная информация о документе" width=20 height=20>
        </a> 
        <a href="marketing/3c0a65635b2bc68b5c43b88421306c37_0.html" title="b">aa</a>
    </td>
</tr>

我需要获取文本

历史/2c0b65635b3ac68a4d53b89521216d26.html 营销/3c0a65635b2bc68b5c43b88421306c37.html

我用python写了一个使用正则表达式的脚本

import re
a = re.compile("[0-9 a-z]{0,15}/[0-9 a-f]{32}.html")
print(a.match(s))

其中s 的值是上面的html 页面。然而,当我使用这个脚本时,我得到了"None"。我哪里做错了?

【问题讨论】:

  • 尝试使用 BeautifulSoup 代替正则表达式。

标签: python html regex html-parsing


【解决方案1】:

Don't use regex for parsing HTML content.

使用专门的工具 - HTML 解析器。

示例(使用BeautifulSoup):

# -*- coding: utf-8 -*-
from bs4 import BeautifulSoup

data = u"""Your HTML here"""

soup = BeautifulSoup(data)
for link in soup.select('td a[href]'):
    print link['href']

打印:

history/2c0b65635b3ac68a4d53b89521216d26.html
history/2c0b65635b3ac68a4d53b89521216d26_0.html
marketing/3c0a65635b2bc68b5c43b88421306c37.html
marketing/3c0a65635b2bc68b5c43b88421306c37_0.html

或者,如果您想获取遵循某种模式的 href 值,请使用:

import re

for link in soup.find_all('a', href=re.compile(r'\w+/\w{32}\.html')):
    print link['href']

其中r'\w+/\w{32}\.html' 是一个正则表达式,将应用于每个找到的a 标记的href 属性。它将匹配一个或多个字母数字字符 (\w+),后跟一个斜杠,后跟正好 32 个字母数字字符 (\w{32}),然后是一个点(\.- 需要转义),然后是 @987654335 @。

DEMO.

【讨论】:

    【解决方案2】:

    你也可以写类似

    >>> soup = BeautifulSoup(html) #html is the string containing the data to be parsed
    >>> for a in soup.select('a'):
    ...     print a['href']
    ... 
    history/2c0b65635b3ac68a4d53b89521216d26.html
    history/2c0b65635b3ac68a4d53b89521216d26_0.html
    marketing/3c0a65635b2bc68b5c43b88421306c37.html
    marketing/3c0a65635b2bc68b5c43b88421306c37_0.html
    

    【讨论】:

      猜你喜欢
      • 2010-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-04
      • 2017-02-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多