sudo easy_install beautifulsoup4
#!/usr/bin/env python from BeautifulSoup import BeautifulSoup #process html #from BeautifulSoup import BeautifulStoneSoup #process xml #import BeautifulSoup #all
doc = ['hello',
'
This is paragraph one of ptyhonclub.org.',
'
This is paragraph two of pythonclub.org.',
'']
soup = BeautifulSoup(''.join(doc))
htmlCharset = "GB2312" soup = BeautifulSoup(respHtml, fromEncoding=htmlCharset)
head = soup.find('head')
#head = soup.head
#head = soup.contents[0].contents[0]
print head
html = soup.contents[0] # <html> ... </html> head = html.contents[0] # <head> ... </head> body = html.contents[1] # <body> ... </body>
body = soup.body html = body.parent # html是body的父亲
head = body.previousSibling # head和body在同一层,是body的前一个兄弟 p1 = body.contents[0] # p1, p2都是body的儿子,我们用contents[0]取得p1 p2 = p1.nextSibling # p2与p1在同一层,是p1的后一个兄弟, 当然body.content[1]也可得到
find(tagname) # 直接搜索名为tagname的tag 如:find('head')
find(list) # 搜索在list中的tag,如: find(['head', 'body'])
find(dict) # 搜索在dict中的tag,如:find({'head':True, 'body':True})
find(re.compile('')) # 搜索符合正则的tag, 如:find(re.compile('^p')) 搜索以p开头的tag
find(lambda) # 搜索函数返回结果为true的tag, 如:find(lambda name: if len(name) == 1) 搜索长度为1的tag
find(True) # 搜索所有tag
find(id='xxx') # 寻找id属性为xxx的
find(attrs={id=re.compile('xxx'), algin='xxx'}) # 寻找id属性符合正则且algin属性为xxx的
find(attrs={id=True, algin=None}) # 寻找有id属性但是没有algin属性的
resp1 = soup.findAll('a', attrs = {'href': match1})
resp2 = soup.findAll('h1', attrs = {'class': match2})
resp3 = soup.findAll('img', attrs = {'id': match3})
print p1.text # u'This is paragraphone.' print p2.text # u'This is paragraphtwo.' # 注意:1,每个tag的text包括了它以及它子孙的text。2,所有text已经被自动转为unicode,如果需要,可以自行转码encode(xxx)
<ul class="listing"> <li class="listing-item"><span class="date">2014-12-03</span><a href="/post/linux_funtion_advance_feature" title="Linux函数高级特性" >Linux函数高级特性</a> </li> <li class="listing-item"><span class="date">2014-12-02</span><a href="/post/cgdb" title="cgdb的使用" >cgdb的使用</a> </li> ... </ul>
#!/usr/bin/env python
# -*- coding: utf-8 -*-
' a http parse test programe '
__author__ = 'kuring lv'
import requests
import bs4
archives_url = "http://kuring.me/archive"
def start_parse(url) :
print "开始获取(%s)内容" % url
response = requests.get(url)
print "获取网页内容完毕"
soup = bs4.BeautifulSoup(response.content.decode("utf-8"))
#soup = bs4.BeautifulSoup(response.text);
# 为了防止漏掉调用close方法,这里使用了with语句
# 写入到文件中的编码为utf-8
with open('archives.txt', 'w') as f :
for archive in soup.select("li.listing-item a") :
f.write(archive.get_text().encode('utf-8') + "\n")
print archive.get_text().encode('utf-8')
# 当命令行运行该模块时,__name__等于'__main__'
# 其他模块导入该模块时,__name__等于'parse_html'
if __name__ == '__main__' :
start_parse(archives_url)
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有