python笔记28-lxml.etree爬取html内容

前言

本篇继续lxml.etree学习,在线访问接口,通过接口返回的html,解析出想要的text文本内容
环境准备:
python 3.6
lxml
requets

定位目标

爬取我的博客首页https://www.cnblogs.com/yoyoketang/左侧栏个人基本信息
先f12抓包,找到该接口地址https://www.cnblogs.com/mvc/blog/news.aspx?blogApp=yoyoketang

# coding:utf-8
import requests
import urllib3
from lxml import etree
urllib3.disable_warnings()

url = "https://www.cnblogs.com/mvc/blog/news.aspx?blogApp=yoyoketang"
r = requests.get(url, verify=False)
# print(r.text)

dom = etree.HTML(r.content.decode("utf-8"))

block = dom.xpath("//*[@id='profile_block']")

# 打印提取到的结果
t = etree.tostring(block[0], encoding="utf-8", pretty_print=True)
print(t.decode("utf-8"))

运行结果

<div id="profile_block">昵称:<a href="https://home.cnblogs.com/u/yoyoketang/">上海-悠悠</a><br/>园龄:<a href="https://home.cnblogs.com/u/yoyoketang/" title="入园时间:2016-11-26">1年9个月</a><br/>粉丝:<a href="https://home.cnblogs.com/u/yoyoketang/followers/">1123</a><br/>关注:<a href="https://home.cnblogs.com/u/yoyoketang/followees/">72</a><div id="p_b_follow"/><script>getFollowStatus('95cb2f22-a6b3-e611-845c-ac853d9f53ac')</script></div>

提取内容

# coding:utf-8
import requests
import urllib3
from lxml import etree
urllib3.disable_warnings()

url = "https://www.cnblogs.com/mvc/blog/news.aspx?blogApp=yoyoketang"
r = requests.get(url, verify=False)
# print(r.text)

dom = etree.HTML(r.content.decode("utf-8"))

block = dom.xpath("//*[@id='profile_block']")


t1 = block[0].xpath('text()')    # 获取当前节点文本元素
print(t1)
t2 = block[0].xpath('a')    # 定位a标签

# 打印结果
for i, j in zip(t1, t2):
    print("%s%s" % (i, j.text))

运行结果:

['昵称:', '园龄:', '粉丝:', '关注:']
昵称:上海-悠悠
园龄:1年9个月
粉丝:1123
关注:72

总结

1.获取当前节点标签名称.tag

print(block[0].tag)

div

2.获取当前节点文本

print(block[0].text)

昵称:

3.获取当前节点元素全部属性dict

print(block[0].attrib)

{'id': 'profile_block'}

4.获取当前节点某个属性

print(block[0].get("id"))

profile_block

5.所有子节点

for i in block[0].iter():
   print(i.text)
profile_block
昵称:
上海-悠悠
None
1年9个月
None
1123
None
72
None
getFollowStatus('95cb2f22-a6b3-e611-845c-ac853d9f53ac')

6.获取当前节点下全部文本

print(block[0].xpath('text()'))

['昵称:', '园龄:', '粉丝:', '关注:']

7.获取本节点和子节点所有文本信息

print(block[0].xpath('.//text()'))

['昵称:', '上海-悠悠', '园龄:', '1年9个月', '粉丝:', '1123', '关注:', '72', "getFollowStatus('95cb2f22-a6b3-e611-845c-ac853d9f53ac')"]

8.获取父节点

print(block[0].getparent().tag)

body

作者:上海-悠悠 python自动化交流 QQ群:779429633

posted @ 2018-09-17 16:23  上海-悠悠  阅读(6362)  评论(0编辑  收藏  举报