直到最后一次出现的正则表达式?

时间:2016-12-12 12:55:17

标签: python regex

我正在使用python,我需要正则表达式来获取网页的联系人链接。所以,我做了<a (.*?)>(.*?)Contacts(.*?)</a>,结果是:

href="/ru/o-nas.html"  id="menu263" title="About">About</a></li><li><a href="/ru/photogallery.html" id="menu645" title="Photo">Photo</a></li><li  class="last"><a href="/ru/kontakt.html" class="last" id="menu583" title="">Contacts

,但我需要上次<a ...喜欢

href="/ru/kontakt.html" class="last" id="menu583" title="">Contacts

我应该使用什么样的正则表达式?

python代码:

match = re.findall('<a (.*?)>(.*?)Contacts(.*?)</a>', body)
if match:
    for m in match:
        print ''.join(m)

2 个答案:

答案 0 :(得分:3)

由于您正在解析HTML,我建议使用BeautifulSoup

# sample html from question
html = '<li><a href="/ru/o-nas.html"  id="menu263" title="About">About</a></li><li><a href="/ru/photogallery.html" id="menu645" title="Photo">Photo</a></li><li  class="last"><a href="/ru/kontakt.html" class="last" id="menu583" title="">Contacts</a></li>'

from bs4 import BeautifulSoup
doc = BeautifulSoup(html)
aTag = doc.find('a', id='menu583') # id for Contacts link
print(aTag['href'])
# '/ru/kontakt.html'

答案 1 :(得分:0)

尝试BeautifulSoup

from BeautifulSoup import BeautifulSoup
import urllib2
import re
links = []
urls  ['www.u1.com','www.u2.om'....]
for url in urls:
    page = urllib2.urlopen(url)
    soup = BeautifulSoup(page)
    for link in soup.findAll('a'):
        if link.string.lower() == 'contact':
            links.append(link.get('href'))