One - One Code All

Blog Content

BeautifulSoup路径选择css选择器

Python   2011-09-10 22:35:47


soup.select("p > a:nth-of-type(2)")

定义和用法
:nth-of-type(n) 选择器匹配属于父元素的特定类型的第 N 个子元素的每个元素.

n 可以是数字、关键词或公式。

提示:请参阅 :nth-child() 选择器,该选择器选取父元素的第 N 个子元素,与类型无关。


实例 1
Odd 和 even 是可用于匹配下标是奇数或偶数的子元素的关键词(第一个子元素的下标是 1)。

在这里,我们为奇数和偶数 p 元素指定两种不同的背景色:

p:nth-of-type(odd)
{
background:#ff0000;
}
p:nth-of-type(even)
{
background:#0000ff;
}


实例 2
使用公式 (an + b)。描述:表示周期的长度,n 是计数器(从 0 开始),b 是偏移值。

在这里,我们指定了下标是 3 的倍数的所有 p 元素的背景色:

p:nth-of-type(3n+0)
{
background:#ff0000;
}

在beautifulsoup中的用法:

找到某个tag标签下的直接子标签

soup.select("head > title")
# [The Dormouse's story]

soup.select("p > a")
# [Elsie,
#  Lacie,
#  Tillie]

soup.select("p > a:nth-of-type(2)")
# [Lacie]

soup.select("p > #link1")
# [Elsie]

soup.select("body > a")
# []


参考:https://www.crummy.com/software/BeautifulSoup/bs4/doc/index.zh.html

css选择器部分。


上一篇:python网页获取request报错Received response with content-encoding: gzip, but failed to decode it
下一篇:python3使用pickle读取文件提示TypeError或者UnicodeDecodeError的解决办法

The minute you think of giving up, think of the reason why you held on so long.