1.利用BeautifulSoup进行html文件的解析很容易,只要掌握一些规则即可
举一个例子吧
首先安装beautifulSoup
解压Beautiful Soup压缩包。
从命令行进入Beautiful Soup解压目录。
运行“python setup.py build”
运行“python setup.py install”
在windows下 如果没有python命令,先将python安装目录加入到环境变量PATH中。
from bs4 import BeautifulSoup 或者 from BeautifulSoup import BeautifulSoup 这两个看那个可以,具体我也没有研究,可能是版本的问题吧
class findurl:
def __init__(self,url):
self.url=url
def read(self):
req=self.url
try:
webpage= urllib2.urlopen(req)
data=webpage.read()
except:
print 'wrong'
return 'error'
self.data = data
def findcom(self):
self.listcom=[]
soup = BeautifulSoup(self.data)
#下面这一句是重点,下面会介绍findAll的具体使用方法
lista=soup.findAll(text=re.compile("com"))
self.listcom=lista
方法findAll
从给定的点开始遍历整个树,并找到满足给定条件所有Tag
以及NavigableString
。 findall
函数原型定义如下:
findAll(name=None, attrs={}, recursive=True, text=None, limit=None, **kwargs)
这些参数会反复的在这个文档中出现。其中最重要的是name
参数 和keywords参数(译注:就是**kwargs参数)。