1.初始化
from pyquery import PyQuery as pq
html_str='''
<div class="wrap">
<div id="container">
<ul class='list'>
<li class="item-0">first item</li>
<li class="item-1" id="di"><a href="link2.html">second item</a></li>
<li class="item-0 active"><a href="link3.html"><span class="bold">third item</span></a></li>
<li class="item-1 active"><a href="link4.html">fourth item</a></li>
<li class="item-0"><a href="link5.html">fifth item</a></li>
</ul>
</div>
</div>
'''
pq_obj = pq(html_str)
2.获取数据
(1)查找子元素,使用find()和children()
#查找id为di的对象
obj_li=pq_obj('#di')#选择到的是一个对象
#find()查找之后的内容中选择想要的子元素 ,和 children('')相同
obj_a = obj_li.find('a')
print(obj_a)
obj_a2 = obj_li.children('a')
print(obj_a2)
结果如下:
(2)查找父元素,使用parent(),parents()
obj_list = pq_obj('.list')
con = obj_list.parent()
print(con)
(3)查找兄弟元素,使用siblings()
li_obj = pq_obj('.list .item-0')
li_obj2 = li_obj.siblings()
print(li_obj2)
(4)获取属性(attr())和文字部分(text())
print('*******获取属性和文字********')
obj_a_href = obj_a.attr('href')
print(obj_a_href)
obj_a_text = obj_a.text()
print(obj_a_text)