Python pyquery

pyquery

A parsing library like jQuery same

initialization

Initialization string

from pyquery import PyQuery as pq
html = ''
doc = pq(html)

Initialization file

from pyquery import PyQuery as pq
doc = pq(filename='')

URL initialization

from pyquery import PyQuery as pq
doc = pq(url='https://cnblogs.com/dbf-')

Selector

from pyquery import PyQuery as pq
html = ''
doc = pq(html)

doc('#i1')          # id 选择器
doc('.c1')          # class 选择器
doc('div')          # 标签选择器
doc('#i1, #i2')     # 组合选择器 id==i1 或 id==i2
doc('#i1.c1')       # 组合选择器 id==i1 且 id==i2
doc('#i1 .c1')      # 层级选择器 id==i1 下所有 class==c1 的标签
doc('div > .c1')    # 层级选择器 id==i1 下一层 class==c1 的标签

Pseudo class selector

from pyquery import PyQuery as pq
html = ''
doc = pq(html)

doc('p:first-child')    # p 标签的第一个子标签
doc('p:last-child')     # p 标签的最后一个子标签
doc('p:nth-child(2)')   # p 标签的第二个子标签
doc('p:gt(2)')          # p 标签的第三个之后的子标签

Other selectors: https: //www.w3school.com.cn/cssref/css_selectors.asp

Finding Elements

Descendant elements

from pyquery import PyQuery as pq
html = ''
doc = pq(html)

doc('#i1').find('.c1')          # == doc('#i1 .c1') 获取 id==i1 元素的子孙元素
doc('#i1').children('.c1')      # == doc('#i1 > .c1') 获取 id==i1 元素的子元素

Ancestor

from pyquery import PyQuery as pq
html = ''
doc = pq(html)

doc('#i1').parent()         # 获取 id==i1 元素的父元素
doc('#i1').parents()        # 获取 id==i1 元素的所有祖先元素
doc('#i1').parents('.c1')   # 获取 id==i1 元素的所有 class==c1 的祖先元素

Siblings

from pyquery import PyQuery as pq
html = ''
doc = pq(html)

doc('#i1').parent()         # 获取 id==i1 元素的父元素
doc('#i1').parents()        # 获取 id==i1 元素的所有祖先元素
doc('#i1').parents('.c1')   # 获取 id==i1 元素的所有 class==c1 的祖先元素

.items() Returns a generator

getting information

Attributes

Obtaining property by property name

from pyquery import PyQuery as pq
html = ''
doc = pq(html)

doc('#i1').attr('href')
doc('#i1').attr.href

content

By .text()can get inside the label text
by .html()you can get the tag html

DOM manipulation

addClass() & removeClass()

By addClass()& removeClass()you can add or delete class for the selected element

attr & css

By attr()& css()can select elements to add, modify attr, css (style attribute)

from pyquery import PyQuery as pq
html = ''
doc = pq(html)

doc('#i1').attr('href')
doc('#i1').attr('href', 'https://cnblogs.com/dbf-')
doc('#i1').css('color', 'red')

remove

By removecan remove selected elements

Guess you like

Origin www.cnblogs.com/dbf-/p/11429060.html