python beautifulsoup分析网页示例,,beautifulsoa
python beautifulsoup分析网页示例,,beautifulsoa
beautifulsoap只有一个py文件,但功能强大,可分析不完整的html页面。下面是用法示例。
安装:
[zhouhh@Hadoop48 test1]$ sudo pip install BeautifulSoup
或者去官网下载:http://www.crummy.com/software/BeautifulSoup/
python操作
>>> from BeautifulSoup import BeautifulSoup>>> doc = ['<html><head><title>用BeautifulSoup对不完整网页分析测试 from abloz.com</title></head>',... '<body><p id="f" class="test" >我的网站 <b>分析</b> from abloz.com.',... '<p id="s" >第二行',... '<a href="http://abloz.com">瀚海星空</a>',... '<a href="http://google.com">google</a>',... '</html>']>>> soup = BeautifulSoup(''.join(doc))>>> soup.html.title<title>用BeautifulSoup对不完整网页分析测试 from abloz.com</title>>>> soup.html.body.p<p id="f" class="test">我的网站 <b>分析</b> from abloz.com.</p>>>> soup.html.title.nameu'title'>>> soup.html.title.textu'\u7528BeautifulSoup\u5bf9\u4e0d\u5b8c\u6574\u7f51\u9875\u5206\u6790\u6d4b\u8bd5 from abloz.com'>>> soup.html.title.stringu'\u7528BeautifulSoup\u5bf9\u4e0d\u5b8c\u6574\u7f51\u9875\u5206\u6790\u6d4b\u8bd5 from abloz.com'>>> print soup.html.title.string用BeautifulSoup对不完整网页分析测试 from abloz.com>>> soup.title<title>用BeautifulSoup对不完整网页分析测试 from abloz.com</title>>>> ps = soup.findAll("p")>>> for p in ps:... print p...<p id="f" class="test">我的网站 <b>分析</b> from abloz.com.</p><p id="s">第二行<a href="http://abloz.com">瀚海星空</a><a href="http://google.com">google</a></p>>>> ps[1]<p id="s">第二行<a href="http://abloz.com">瀚海星空</a><a href="http://google.com">google</a></p>>>> ps[0]<p id="f" class="test">我的网站 <b>分析</b> from abloz.com.</p>>>> aes=soup.findAll("a")>>> for a in aes:... print a.text... print a["href"]...瀚海星空http://abloz.comgooglehttp://google.com>>> import re>>> ts = soup.findAll(text=re.compile("分析"))>>> print ts[]>>> ts = soup.findAll(text=re.compile("goo"))>>> print ts[u'google']
注意支持中文需要转为unicode
>>> ts = soup.findAll(text=re.compile(u"分析"))>>> ts[u'\u7528BeautifulSoup\u5bf9\u4e0d\u5b8c\u6574\u7f51\u9875\u5206\u6790\u6d4b\u8bd5 from abloz.com', u'\u5206\u6790']>>> for t in ts:... print t...
用BeautifulSoup对不完整网页分析测试 from abloz.com
分析
>>> ids = soup.findAll(id=re.compile("f"))>>> ids[<p id="f" class="test">我的网站 <b>分析</b> from abloz.com.</p>]
和上一个等价的方式
>>> ids = soup.findAll(attrs={"id":re.compile("f")})>>> ids[<p id="f" class="test">我的网站 <b>分析</b> from abloz.com.</p>]>>> soup.find("p")<p id="f" class="test">我的网站 <b>分析</b> from abloz.com.</p>>>> soup.find("a")<a href="http://abloz.com">瀚海星空</a>
参考:
中文文档:http://www.crummy.com/software/BeautifulSoup/bs3/documentation.zh.html
官网:http://www.crummy.com/software/BeautifulSoup/
相关内容
- python破解验证码,python验证码,有开源的tesserac
- python easy_install 发生Unable to find vcvarsall.bat错误的处理方
- python错误处理记录完整的异常堆栈信息,python错误堆栈
- python使用深拷贝和浅拷贝复制对象,python拷贝,使用co
- easy_install 升级包,easy_install,easy_install
- easy_install 的n种用法,easy_install用法,easy_install
- python连接redis,pythonredis,首先需要通过easy_i
- python编写的FTP弱口令扫描器 python FTP暴力破解部分代码
- 把traceback信息传递给字符串,并且发送给邮箱,traceb
- python 生成java执行的shell文件,pythonshell,我有这么一个
评论关闭