html=etree.HTML(content)
#-*-coding:UTF-8-*-
from lxml import etree #xpath是etree内的模块
import sys
reload(sys)
sys.setdefaultencoding('utf8')
file=open('a.html','r')
content=file.read()
html=etree.HTML(content) #将html内容转换为树状结构的可访问内容
file.close()
####开始读取html内的节点内容#######
# / 表示读取当前节点下所有子节点
# text() 读取节点内内容
# @ 读取节点属性值 等价于 node.get()
# // 获取当前所处的节点中所有要找的节点
#nodename 直接获取这个节点下的所有子节点
# . 选取当前节点
# .. 选取当前节点的父节点
title=html.xpath('/html/head/title/text()')
div=html.xpath('/html/head/link/@href') #['https://static.zhipin.com/zhipin-geek/v341/web/geek/css/main.css', 'https://www.zhipin.com/c101270100/?query=%E9%85%8D%E7%BD%AE%E7%AE%A1%E7%90%86', 'https://m.zhipin.com/c101270100/?query=%E9%85%8D%E7%BD%AE%E7%AE%A1%E7%90%86']
link=html.xpath('//link')#[<Element link at 0x460b088>, <Element link at 0x460b408>, <Element link at 0x460a348>]
linkn=html.xpath('//h3/text()')
allnode=html.xpath('head')
fathernode=html.xpath('//head/..')
print "当前访问页面是:"+title[0].decode('utf-8') #解码
#print (divs[0].decode('utf-8') for divs in div)
print div
print link
print (linkns[0].decode('utf-8') for linkns in linkn)
###批量获取内容信息##################
list=html.xpath('//li/text()')
for i in list:
if i:
print i
else:
continue
print allnode
print fathernode
linkn=html.xpath('//div[1]/h3/text()') #第一个div下的h3的文本内容
last=html.xpath('//div[last()]/h3/text()')
pos=html.xpath('//div[position()<3]/h3/text()') #前两个
html.xpath('//div[last()-2]/h3/text()')#后两个 从最后向前数两个
for i in linkn:
if i:
print i
else:
continue
for v in last:
print "***"
print v
########节点轴的选择##########################
link=html.xpath('//link[1]')
zuxian=html.xpath('//h3[1]/ancestor::*') #获取第一个h3的所有祖先节点,*表示所有
#[<Element html at 0x44bbbc8>, , <Element body at 0x457c948>, <Element div at 0x457c988>,。。。
print zuxian
zuxian=html.xpath('//h3[1]/ancestor::ul') #获取祖先中的ul节点
#[<Element ul at 0x45f1848>]
print zuxian
shuxin=html.xpath('//h3[1]/li/attribute::*') #获取li的所有属性值
shuxin=html.xpath('//h3[1]/li/attribute::herf') #获取li的herf属性值
child=html.xpath('//div[1]/li/child::h3') #获取子节点中的h3节点
child=html.xpath('//div[1]/li/child::h3[@href="http***"]') #获取子节点中的h3节点
geta=html.xpath('//h3[1]/li[@href="http/..."]/text()')#根据属性来查询节点## 获取满足属性值的内容
######节点的遍历############
linkn=html.xpath('//div/h3') #第一个div下的h3的文本内容
for i in linkn:
if i:
print i.xpath('text()')[0].decode('utf-8')
else:
continue
###############yield关键字使用###########
def useyield():
shuxin = html.xpath('//h3[1]/li/attribute::href') # 获取li的所有属性值
for item in shuxin:
yield {
'shuxinitem':item
}
def usefunc():
a=useyield() #
for i in a:
print i
usefunc()