使用 PyQuery

PyQuery 用法:

(1) 前面我们爬取一个网页,都是使用正则表达式来提取想要的信息,但是这种方式比较复杂,一旦有一个地方写错,就匹配不出来了,因此我们可以使用 PyQuery
(2) PyQuery 是一个网页解析库,如果你觉得正则写起来太麻烦,如果你觉得 BeautifulSoup 语法太难记,如果你熟悉 jQuery 的语法,那么,PyQuery就是你绝佳的选择
(3) 提供了和 jQuery 类似的语法来解析 HTML 文梢, 支持 CSS 选择器,安装方法:pip3 install pyquery

from pyquery import PyQuery as pq

html = '''
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>首页</title>
    </head>
    <body class="item">
        <p class="item" id="username">This is your username</p>
        <p class="item" id="password">This is your password</p>
    </body>
    </html>
'''

doc = pq(html)                     # 初始化一个PyQuery对象,可以传入字符串 、传入URL 、传入文件名
                                   # 也可以传入URL或文件名:pq(url="http://www.baidu.com/") 、pq(filename="./index.html")
result = doc('title')              # 表示提取<title>节点,结果为:<title>首页</title>
result = doc('.item')              # 可以基于CSS选择器来进行提取,这里表示提取class="item"的所有节点
result = doc.find('p')             # find()方法会将符合条件的所有节点选择出来,这里表示提取所有<p>节点
result = doc.find('p').attr('id')  # attr()用于获取节点的属性值,这里表示获取id属性的值,结果为:username
result = doc.find('p').text())     # text()用于获取节点的文本内容,结果为:This is your username This is your password

    

猜你喜欢

转载自www.cnblogs.com/pzk7788/p/10534707.html