python - 使用 BS4 构造最短的有效 css 选择器
问题描述
我正在使用以下函数构造一个使用 BS4 的 css 选择器:
def nth_of_type(elem):
count, curr = 0, 0
for i, e in enumerate(elem.find_parent().find_all(recursive=False), 1):
if e.name == elem.name:
count += 1
if e == elem:
curr = i
return '' if count == 1 else ':nth-child({})'.format(curr)
def getCssPath(elem):
rv = [elem.name + nth_of_type(elem)]
while True:
elem = elem.find_parent()
if not elem or elem.name == '[document]':
return '>'.join(rv[::-1])
rv.append(elem.name + nth_of_type(elem))
因此,如果我使用以下方法抓取页面:
page_r = requests.get('<my url>')
page_soup = BeautifulSoup(page_r.content, 'html.parser')
elements = page_soup.find_all('a')
print(getCssPath(elements[0])
# html>body>div:nth-child(2)>div:nth-child(6)>div>div>main>article>div>div:nth-child(1)>div:nth-child(1)>div>div>div>div:nth-child(2)>div:nth-child(1)>div>div>div>div>div:nth-child(1)>div:nth-child(2)>div>div:nth-child(4)>a`
但这很长,所以我想获得最短的 CSS 选择器。类似于您在 chrome 中右键单击元素并执行Copy > Selector
. 这可能涉及类和 ID 等。
是否已经有任何 BS4 功能来获得它,或者应该如何修改这个功能来获得它?
解决方案
推荐阅读
- sql-server - 如何在版本 12 或 13 上恢复 sql 备份文件版本 8?
- javascript - 如何使用另一个 json 数组过滤 json 数组?
- javascript - 如何使用三个js检查动态变化的布尔值
- html - 如何在textarea中从顶部边框边缘设置文本
- qt - 不推荐使用 QtCharts axisX()
- java - 使用@SpringBootTest时如何在测试类中自动装配bean
- javascript - 二维装箱算法
- hibernate - JPA 查询不返回与日志中的查询相同的结果
- reactjs - 如何启动多个调度
- c++ - 特征读取和写入 LLT 分解到文件