从网站中提取特定行

Extraction Specific Lines From A Website

</span>
                    <div class="clearB paddingT5px"></div>
                    <small>
                        10/12/2015 5:49:00 PM -  Seeking Alpha
                    </small>
                    <div class="clearB paddingT10px"></div>

假设我有一个网站的源代码,其中一部分看起来像这样。我正在尝试获取 "small" 和“/small”之间的界线。整个网页中有很多这样的行,包围在"small"和“/small”之间。我想提取 "small" 和“/small”之间的所有行。

我正在尝试使用如下所示的 'regex' 函数

regex = '<small>(.+?)</small>'
datestamp = re.compile(regex)
urls = re.findall(datestamp, htmltext)

这个returns只有一个空白space。请就此提出建议。

您可以通过以下两种方式解决此问题:

首先使用正则表达式,不推荐:

import re

html = """</span>
    <div class="clearB paddingT5px"></div>
    <small>
        10/12/2015 5:49:00 PM -  Seeking Alpha
    </small>
    <div class="clearB paddingT10px"></div>"""

for item in re.findall('\<small\>\s*(.*?)\s*\<\/small\>', html, re.I+re.M):
    print '"{}"'.format(item)

其次使用 BeautifulSoup 之类的东西为您解析 HTML:

from bs4 import BeautifulSoup

soup = BeautifulSoup(html, "html.parser")
for item in soup.find_all("small"):
    print '"{}"'.format(item.text.strip())

为两者提供以下输出:

"10/12/2015 5:49:00 PM -  Seeking Alpha"

这里使用xml.etree。有了它,您可以从网页中获取 html 数据,并使用 urllib2 return 任何您想要的标签......就像这样。

import urllib2
from xml.etree import ElementTree

url = whateverwebpageyouarelookingin
request = urllib2.Request(url, headers={"Accept" : "application/xml"})
u = urllib2.urlopen(request)
tree = ElementTree.parse(u)
rootElem = tree.getroot()
yourdata = rootElem.findall("small")  
print yourdata