Table of Contents
https://cuiqingcai.com/5551.html
基本CSS选择器
查找节点
find() 查找子孙节点
children() 查找子节点
parent() 查找父节点
siblings() 兄弟节点
遍历
单个节点可以直接打印输出
多个节点需要调用items()方法
获取信息
获取属性: 调用 attr() 方法获取属性 或 attr 属性获取
获取文本: text() 获取节点内所有文本信息 html() 获取第一个节点内的html信息
节点操作
addClass 和 removeClass
attr、text 和 html
remove() 移除
伪类选择器
html = '''
- first item
- second item
- third item
- fourth item
- fifth item
'''
from pyquery import PyQuery as pq
doc = pq(html)
print(doc('#container .list a'))
print(doc('.list span'))
print(doc('.bold'))
# second itemthird itemfourth itemfifth item
# third item
# third item
html = '''
- first item
- second item
- third item
- fourth item
- fifth item
'''
from pyquery import PyQuery as pq
doc = pq(html)
# 子孙节点
print(doc('.list').find('.active'))
# 子节点
print(doc('#container').children('.active'))
# 子节点
print(doc('.list').children('.active'))
# 父节点
print(doc('.bold').parent())
# 兄弟节点
print(doc('.item-0.active').siblings())
items()
方法
html = '''
- first item
- second item
- third item
- fourth item
- fifth item
'''
from pyquery import PyQuery as pq
doc = pq(html)
# 单个节点
li = doc('.item-0.active')
print(li)
print(str(li))
# 多个节点
print('*'*20)
lis = doc('li').items()
for i in lis:
print(i)
html = '''
- first item
- second item
- third item
- fourth item
- fifth item
'''
from pyquery import PyQuery as pq
doc = pq(html)
# attr方法 和 attr属性
a = doc('.item-1.active a')
print(a.attr('href'))
print(a.attr.href)
# attr方法 和 attr属性
print(list(doc('div .item-0').items())[2].find('a').attr('href'))
print(list(doc('div .item-0').items())[2].find('a').attr.href)
# text() 获取文本
print(doc('.item-1.active a').text())
print(doc('.item-1.active a').html())
# 获取第一个 li 的文本
print(doc('li').html())
# 获取所有 li 的文本
print(doc('li').text())
addClass
和 removeClass
html = '''
- first item
- second item
- third item
- fourth item
- fifth item
'''
from pyquery import PyQuery as pq
doc = pq(html)
li = doc('.item-0.active')
print(li)
# 移除 class
li.removeClass('active')
print(li)
# 添加 class
li.addClass('test')
print(li)
attr
、text
和 html
html = '''
'''
from pyquery import PyQuery as pq
doc = pq(html)
li = doc('.item-0.active')
print(li)
# 添加 name
li.attr('name', 'link')
print(li)
# 修改 text 纯文本
li.text('changed item')
print(li)
# 修改 html 文本
li.html('changed item')
print(li)
html = '''
Hello, World
This is a paragraph.
'''
from pyquery import PyQuery as pq
doc = pq(html)
wrap = doc('.wrap')
print(wrap.text())
wrap.find('p').remove()
print(wrap)
print(wrap.text())
http://www.w3school.com.cn/css/index.asp
html = '''
- first item
- second item
- third item
- fourth item
- fifth item
'''
from pyquery import PyQuery as pq
doc = pq(html)
li = doc('li:first-child')
print(li)
li = doc('li:last-child')
print(li)
li = doc('li:nth-child(2)')
print(li)
li = doc('li:gt(2)')
print(li)
li = doc('li:nth-child(2n)')
print(li)