[英]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>
假设我有一个网站的源代码,其中一部分看起来像这样。 我试图使“小”和“ /小”之间的界限。 在整个网页中,有很多这样的行,包含在“小”和“ /小”之间。 我想提取介于“小”和“ /小”之间的所有行。
我正在尝试使用看起来像这样的“正则表达式”功能
regex = '<small>(.+?)</small>'
datestamp = re.compile(regex)
urls = re.findall(datestamp, htmltext)
这仅返回空白。 请给我建议。
您可以通过以下两种方法来解决此问题:
首先使用正则表达式,不建议:
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 .....返回想要的任何标签,就像这样。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.