Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/278.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用BS4构造最短的有效css选择器_Python_Web Scraping_Beautifulsoup_Css Selectors - Fatal编程技术网

Python 使用BS4构造最短的有效css选择器

Python 使用BS4构造最短的有效css选择器,python,web-scraping,beautifulsoup,css-selectors,Python,Web Scraping,Beautifulsoup,Css Selectors,我正在使用以下函数使用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 re

我正在使用以下函数使用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`
page\r=requests.get(“”)
page\u soup=BeautifulSoup(page\r.content,'html.parser')
elements=page\u soup.find\u all('a'))
打印(getCssPath(元素[0])
#html>body>div:n个孩子(2)>div:n个孩子(6)>div>div>div>main>article>div>div:n个孩子(1)>div:n个孩子(1)>div:n个孩子(2)>div:n个孩子(1)>div:n个孩子(1)>div:n个孩子(2)>div>div:n个孩子(4)>a`
但是这很长,所以我想得到最短的CSS选择器。类似于在chrome中右键单击元素并执行
Copy>selector
。这可能涉及类和ID等


是否已有任何BS4函数可以获取该值,或者应该如何修改该函数以获取该值?

您可以尝试使用
elem.attrs.get('class')
elem.attrs.get('id'))
但它仍然需要代码来检查选择器是否只获取一项。我想我没有在中显示此项的函数,所以您必须自己编写。您可以尝试使用
elem.attrs.get('class')
elem.attrs.get('id'))
但它仍然需要代码来检查选择器是否只获取一项。我想我没有在中显示此项的函数,所以您必须自己编写。