Python学习--第九天

一、通过pyquery定位如下html源码中的第二对儿ul中的li文本(使用CSS选择器实现,不要用下标索引)。

from pyquery import PyQuery
html = """
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
"""
num = PyQuery(html) print(num('ul:last-child').text())

运行结果:

"F:\Python 3.8.0\python.exe" 
9
10
Process finished with exit code 0

二、对上例中所有的li节点,奇数节点添加class值:active-0,偶数节点添加class值:active-1。

from pyquery import PyQuery

html = """
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
"""
num = PyQuery(html) Odd_num = num('li:nth-child(2n-1)') #奇数 print(Odd_num.addClass('active-0'), end="") #添加active-0 Even_num = num('li:nth-child(2n)') #偶数 print(Even_num.addClass('active-1'), end="") #添加active-1

运行结果:

"F:\Python 3.8.0\python.exe" 
<li class="active-0">1</li>
        <li class="active-0">3</li>
        <li class="active-0">5</li>
        <li class="active-0">7</li>
        <li class="active-0">9</li>
        <li class="active-1">2</li>
        <li class="active-1">4</li>
        <li class="active-1">6</li>
        <li class="active-1">8</li>
    <li class="active-1">10</li>
Process finished with exit code 0

你可能感兴趣的:(Python,python)