Python 2.7和BS4中的$、^和*符号有什么作用?

3
Selenium文档中,他们在下面的代码中使用了^$*这些特殊符号,并放在=运算符之前,但没有解释为什么要使用这些特殊符号
soup.select('a[href="http://example.com/elsie"]')
# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>]

soup.select('a[href^="http://example.com/"]')
# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
#  <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>,
#  <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]

soup.select('a[href$="tillie"]')
# [<a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]

soup.select('a[href*=".com/el"]')
# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>]
2个回答

7

这些是从CSS 3中改编的子字符串匹配属性选择器

  • =仅在给定值等于元素属性值时匹配。
  • ^=仅在给定值是元素属性值的前缀时匹配。
  • $=仅在给定值是元素属性值的后缀时匹配。
  • *=仅在给定值包含在元素属性值中时匹配。

在您的情况下:

  • a[href="http://example.com/elsie"] 选取任何 a 元素,其 href 属性值等于 http://example.com/elsie
  • a[href^="http://example.com/"] 选取任何 a 元素,其 href 属性值以 http://example.com/ 开头。
  • a[href$="tillie"] 选取任何 a 元素,其 href 属性值以 tillie 结尾。
  • a[href*=".com/el"] 选取任何 a 元素,其 href 属性值包含 .com/el

那个链接在我的桌面上打不开。你能告诉我它在我的例子中是做什么的吗? - Arup Rakshit
哦!太棒了,它打开了!我明白了概念!谢谢你的帮助 :) - Arup Rakshit
我能否了解一下"Push data"的概念? - Arup Rakshit

3

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接