Python学习 Day45 数据解析-pyquery 09

pyquery解析数据

一、pyquery概述

  • pyquery库是jQuery的Python实现,能够以jQuery的语法来操作解析HTML文档,易用性和解析速度都很好
  • 前提条件:了解CSS选择器以及jQuery
  • 非Python标准模块,需要安装
    安装方式:pip install pyquery -i http://pypi.douban.com/simple --trusted-host pypi.douban.com
    测试方式:import pyquery

二、pyquery的初始化方式

(一)字符串方式

语法

from pyquery import PyQuery as pq
doc = pq(str)
print(doc)
print(type(doc))

具体代码

from pyquery import PyQuery as pq
print('--------------第一种方式:字符串-----------------')
html = '''
        <html>
            <head>
                <title>PyQuery</title>
            </head>
            <body>
                <h1>水面清圆</h1>
            </body>
        </html>
'''
#创建pyquery对象,实际上就是在进行一个类型转换,将str类型转换为PyQuery类型,才能使用pq对应的方法
doc = pq(html)  #输出HTML中的内容
print(type(html)) #字符串类型 <class 'str'>
print(type(doc)) #<class 'pyquery.pyquery.PyQuery'>
print(doc('title'))
--------------第一种方式:字符串-----------------
<class 'str'>
<class 'pyquery.pyquery.PyQuery'>
<title>PyQuery</title>
            

Process finished with exit code 0

(二)URL方式

语法

from pyquery import PyQuery as pq
doc = pq(url='http://www.baidu.com',encoding='utf-8')
print(type(doc))
print(doc('title')

具体代码

from pyquery import PyQuery as pq
print('---------------第二种方式:URL------------------------')
#创建一个pq对象
doc = pq(url = 'http://www.baidu.com',encoding = 'utf-8') #编码解决乱码问题
print(doc)
print('\n标签名称:',doc('title')) #括号中写上待查询的标签名
---------------第二种方式:URL------------------------
<html> <head><meta http-equiv="content-type" content="text/html;charset=utf-8"/><meta http-equiv="X-UA-Compatible" content="IE=Edge"/><meta content="always" name="referrer"/><link rel="stylesheet" type="text/css" href="http://s1.bdstatic.com/r/www/cache/bdorz/baidu.min.css"/><title>百度一下,你就知道</title></head> <body link="#0000cc"> <div id="wrapper"> <div id="head"> <div class="head_wrapper"> <div class="s_form"> <div class="s_form_wrapper"> <div id="lg"> <img hidefocus="true" src="//www.baidu.com/img/bd_logo1.png" width="270" height="129"/> </div> <form id="form" name="f" action="//www.baidu.com/s" class="fm"> <input type="hidden" name="bdorz_come" value="1"/> <input type="hidden" name="ie" value="utf-8"/> <input type="hidden" name="f" value="8"/> <input type="hidden" name="rsv_bp" value="1"/> <input type="hidden" name="rsv_idx" value="1"/> <input type="hidden" name="tn" value="baidu"/><span class="bg s_ipt_wr"><input id="kw" name="wd" class="s_ipt" value="" maxlength="255" autocomplete="off" autofocus=""/></span><span class="bg s_btn_wr"><input type="submit" id="su" value="百度一下" class="bg s_btn"/></span> </form> </div> </div> <div id="u1"> <a href="http://news.baidu.com" name="tj_trnews" class="mnav">新闻</a> <a href="http://www.hao123.com" name="tj_trhao123" class="mnav">hao123</a> <a href="http://map.baidu.com" name="tj_trmap" class="mnav">地图</a> <a href="http://v.baidu.com" name="tj_trvideo" class="mnav">视频</a> <a href="http://tieba.baidu.com" name="tj_trtieba" class="mnav">贴吧</a> <noscript> <a href="http://www.baidu.com/bdorz/login.gif?login&amp;tpl=mn&amp;u=http%3A%2F%2Fwww.baidu.com%2f%3fbdorz_come%3d1" name="tj_login" class="lb">登录</a> </noscript> <script>document.write('&lt;a href="http://www.baidu.com/bdorz/login.gif?login&amp;tpl=mn&amp;u='+ encodeURIComponent(window.location.href+ (window.location.search === "" ? "?" : "&amp;")+ "bdorz_come=1")+ '" name="tj_login" class="lb"&gt;登录&lt;/a&gt;');</script> <a href="//www.baidu.com/more/" name="tj_briicon" class="bri" style="display: block;">更多产品</a> </div> </div> </div> <div id="ftCon"> <div id="ftConw"> <p id="lh"> <a href="http://home.baidu.com">关于百度</a> <a href="http://ir.baidu.com">About Baidu</a> </p> <p id="cp">©2017 Baidu <a href="http://www.baidu.com/duty/">使用百度前必读</a>  <a href="http://jianyi.baidu.com/" class="cp-feedback">意见反馈</a> 京ICP证030173<img src="//www.baidu.com/img/gs.gif"/> </p> </div> </div> </div> </body> </html>

标签名称: <title>百度一下,你就知道</title>

Process finished with exit code 0

(三)文件

前提:需要有一个HTML文件
在这里插入图片描述
语法

from pyquery import PyQuery as pq
doc = pq(filename = 'demo.html')
print(type(doc))

具体代码

from pyquery import PyQuery as pq
doc = pq(filename='demo.html')
print(doc)
print(doc('h1'))
<html>
            <head>
                <title>PyQuery</title>
            </head>
            <body>
                <h1>姘撮潰娓呭渾</h1>
            </body>
</html>
<h1>姘撮潰娓呭渾</h1>
            

Process finished with exit code 0

三、pyquery解析数据

pyquery的使用

提取数据 举例
获取当前节点 doc(’#main’)
获取子节点 doc(’#main’).childern()
获取父节点 doc(’#main’).parent()
获取兄弟节点 doc(’#main’).siblings()
获取属性 doc(’#main’).attr(‘href’)
获取内容 doc(’#main’).html() / doc(’#main’).text()

代码

from pyquery import PyQuery as pq
html = '''
        <html>
            <head>
                <title>PyQuery</title>
            </head>
            <body>
                <div id='main'>
                    <a href='https://www.baidu.com'>百度一下,你就知道</a>
                    <h1>水面清圆</h1>
                </div>
                <h2>一一风荷举</h2>
            </body>
        </html>
'''
#初始化pyquery对象
doc = pq(html)
#获取当前节点
print('获取当前节点:\n',doc('#main'))
#获取父节点
print('获取父节点:\n',doc('#main').parent())
#获取子节点
print('获取子节点:\n',doc('#main').children())
#获取兄弟节点
print('获取兄弟节点:\n',doc('#main').siblings())
#获取属性
print('获取属性:\n',doc('a').attr('href'))
#获取标签内容
print('获取标签内容html:\n',doc('#main').html())
print('获取标签内容text:\n',doc('#main').text())
获取当前节点:
 <div id="main">
                    <a href="https://www.baidu.com">百度一下,你就知道</a>
                    <h1>水面清圆</h1>
                </div>
                
获取父节点:
 <body>
                <div id="main">
                    <a href="https://www.baidu.com">百度一下,你就知道</a>
                    <h1>水面清圆</h1>
                </div>
                <h2>一一风荷举</h2>
            </body>
        
获取子节点:
 <a href="https://www.baidu.com">百度一下,你就知道</a>
                    <h1>水面清圆</h1>
                
获取兄弟节点:
 <h2>一一风荷举</h2>
            
获取属性:
 https://www.baidu.com
获取标签内容html:
 
                    <a href="https://www.baidu.com">百度一下,你就知道</a>
                    <h1>水面清圆</h1>
                
获取标签内容text:
 百度一下,你就知道
水面清圆

Process finished with exit code 0


案例

获取小说名称
在这里插入图片描述
获取小说作者
在这里插入图片描述
由于作者所在的几个标签没有规律,在这里并没有做到一一对应

#获取小说作者
authors = doc('p.author a')
authors_lst = []
for index in range(len(authors)):
    if index%2 == 0:
        authors_lst.append(authors[index].text)
#print(authors_lst)

在这里插入图片描述
具体代码

from pyquery import PyQuery as pq
import requests

#需要爬取的网址
url = 'https://www.qidian.com/finish'
#加入请求头,模拟浏览器
headers = {
    
    'user-agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.128 Safari/537.36'}
#发送请求
resp = requests.get(url,headers=headers)
#print(resp.text)
#pyquery进行数据解析
doc = pq(resp.text) #使用字符串初始化方式初始化pyquery对象
#提取内容:小说名(h4里的a标签)
#a_tag = doc('h4 a')
#print(a_tag)

#使用列表生成式存储小说名字
names = [a.text for a in doc('h4 a')]
#print(names)

#获取小说作者
authors = doc('p.author a')
authors_lst = []
for index in range(len(authors)):
    if index%2 == 0:
        authors_lst.append(authors[index].text)
#print(authors_lst)

#作者一一对应(由于标签没有规律,没有完成)
for name,author in zip(names,authors_lst):
    print(name,':',author)

没有一一对应,多获取了除作者之外的标签

沧元图 : 我吃西红柿
诡秘之主 : 高武世界
万族之劫 : 玄幻
我师兄实在太稳健了 : 轻小说
烂柯棋缘 : 都市
我有一座冒险屋 : 言归正传
第一序列 : 神话修真
最强孝心系统 : 真费事
全球高武 : 古典仙侠
吞噬星空 : 悬疑
大王饶命 : 轻小说
世子很凶 : 都市
修真聊天群 : 打死不鸽
牧神记 : 东方玄幻
妖魔哪里走 : 老鹰吃小鸡
九星毒奶 : 都市异能
学霸的黑科技系统 : 我吃西红柿
当医生开了外挂 : 未来世界
凡人修仙传 : 都市
完美世界 : 轻小说

Process finished with exit code 0

Guess you like

Origin blog.csdn.net/ShengXIABai/article/details/115733331
Recommended