糗事百科案例(使用 xpath模块)

来源:互联网 发布:软件项目标书 编辑:程序博客网 时间:2024/06/05 16:42

通过一个案列先了解下json与python之间的转换关系

#json解析库,对应到lxmlimport json#json的解析语法,对应到xpathimport jsonpathimport urllib2url="http://www.lagou.com/lbs/getAllCitySearchLabels.json"headers={"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36"}request=urllib2.Request(url,headers=headers)response=urllib2.urlopen(request)#返回json文件里面的内容,返回的格式是字符串html=response.read()# print html.encode("gb18030")#把json转换成python格式的unicode字符串unicodestr=json.loads(html)city_list=jsonpath.jsonpath(unicodestr,"$..name")#从当前节点的任意位置匹配name,返回一个列表# for i in city_list:# print i#dumps默认中文为ascii编码格式#把python格式的转换为json格式的,返回的是unicode字符串#禁用ascii编码格式,返回的unicode字符串,方便使用(转码)array=json.dumps(city_list,ensure_ascii=False)with open("city_list.txt","w") as f:f.write(array.encode("gb18030"))

爬糗事百科获取每个段子的用户名,每个段子中的图片,还有每个段子的内容,每个段子的点赞人数还有评论人数

# https://www.qiushibaike.com/8hr/page/3/# //div[contains(@id,"qiushi_tag")]# 段子名字# .//h2[1]#在当前节点下找,所以直接是.就行# 点赞人数# ./div/span/i# 评论人数# ./div/span/a/i# 段子内容# .//div[@class="content"]/span# 图片链接# .//div[@class="thumb"]//@srcimport urllib2import jsonfrom lxml import etreeurl="https://www.qiushibaike.com/8hr/page/3/"headers={"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36"}request=urllib2.Request(url,headers=headers)response=urllib2.urlopen(request)html=response.read()#把htmll转换成html domtext=etree.HTML(html)#返回所有 段子的节点位置,contains()模糊查询方法,第一个参数是要匹配的标签,第二个参数是标签名部分内容node_list=text.xpath('//div[contains(@id,"qiushi_tag")]')data={}for node in node_list:#用户名username=(node.xpath(".//h2"))[0].text#因为node.xpath(".//h2")返回的是列表,里面装的是content,因为一个段子只有一个content,所以这个列表里面就有一个content,我们用[0],把这个content取出来#段子内容(取出标签下的内容,所以要加text)content=(node.xpath('.//div[@class="content"]/span'))[0].text#取出标签下的内容,点赞的人数dianzan=(node.xpath('./div/span/i'))[0].text#评论的内容pinglun=(node.xpath('./div/span/a/i'))[0].text#段子中图片的urlimg=(node.xpath('.//div[@class="thumb"]//@src'))if len(img)>=1:img="http:"+img[0]data={"username":username,"content":content,"dianzan":dianzan,"pinglun":pinglun,"img":img}we=json.dumps(data,ensure_ascii=False)#把python格式的转换为json格式,此时转换成了字符串,就可以写入糗事段子.txt文件中了with open(u"糗事段子.txt","a") as f:f.write(we+'\n')#每个段子之间换行