簡體   English   中英

使用正則表達式提取HTML數據

[英]Extract html data using regular expressions

我有一個看起來像這樣的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 marketing / 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" 我哪里做錯了?

不要使用正則表達式來解析HTML內容。

使用專用工具-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'是一個正則表達式,將被應用到href每屬性a發現標記 它會匹配一個或多個字母數字字符( \\w+ ),后跟一個斜杠,然后是正好32個字母數字字符( \\w{32} ),再跟一個點( \\. 。-需要轉義),然后是html

DEMO。

您也可以寫類似

>>> 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

暫無
暫無

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

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