首页 > 解决方案 > 使用 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 功能来获得它,或者应该如何修改这个功能来获得它?

标签: pythonweb-scrapingbeautifulsoupcss-selectors

解决方案


推荐阅读