bs4:可以解析为lxml格式,也可以解析为html格式
基础使用
#-*-coding:UTF-8-*-
from bs4 import BeautifulSoup
import os,sys
import json
# reload(sys)
# sys.setdefaultencoding('utf8')
if os.path.exists('a.html'):
print "file not exist!!"
# excelfile='C:\Users\Desktop\get_owner.xls'
# if os.access(excelfile,os.F_OK):
# os.remove(excelfile)
file=open('a.html','r')
content=file.read()
file.close()
###用bs4解析html网页####
#html=BeautifulSoup(content,'html.parser') #解析为html的格式
html=BeautifulSoup(content,'lxml') #解析为lxml的格式
#print html.prettify() ##格式化输出
######################获取节点的几种方式######3
###节点选择器##
print html.li #获取的第一个li节点
print html.li.attrs #获取第一个li节点的所有属性 返回字典格式
#print html.li.attrs['href'] #指定属性获取值
print html.li.a.string #获取第一个li中a节点的文本内容
print html.li.a.name #获取节点名
###方法选择器##
print html.find(name='li')#获取的第一个li节点
print html.find(attrs={'href':'a'})#获取第一个属性值匹配的节点
print html.find_all(attrs={'href':'a'})#获取所有属性值匹配的节点
print html.findAll('li',attrs={'href':'a'})
###css选择器##
print html.select('li')
print html.select('li.db p').get_text() #获取class为db的li标签下的p标签
#print html.findAll('li')
print html.select('#header')
print html.select('.logo')
list=html.select('div li h3 a') #获取div下li下h3节点
for i in list:
print i
print i.attrs['href']+' '+i.string
yield关键字使用
###############yield关键字使用###########
def useyield():
shuxin = html.select('div li h3 a') #获取div下li下h3节点
for item in shuxin:
if 'href' not in item.attrs: #判断是否有href属性
continue
yield {
'title':item.get('title'),
'href':item.get('href')
}
#yield关键字相当于每组数据都形成一个字典格式,所有字典形成一个对象,返回给调用的函数
#每解析出来一个数据就返回到i一次
def dictojson(content):
print json.dumps(content,ensure_ascii=False) #dumps将字典格式输出为json格式(即字符串),ensure_ascii=False表示接收中文可以用asc码
def usefunc():
a=useyield() #
for i in a:
print i
dictojson(i)
usefunc()