Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/306.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 find_all()语句中的筛选函数问题_Python_Function_Beautifulsoup_Tags_Filtering - Fatal编程技术网

Python中BS4 find_all()语句中的筛选函数问题

Python中BS4 find_all()语句中的筛选函数问题,python,function,beautifulsoup,tags,filtering,Python,Function,Beautifulsoup,Tags,Filtering,我正在抓取一个HTML网页。我正在Mac(Sierra)上使用BeautifulSoup库(4.6.0)和Python(3.7) 除此之外,我看到了一堆具有类属性的'div'标记。一些'div'标记带有多个class属性值。现在,我想根据标记名和类属性值进行筛选,例如,我想查找具有class='a'但不具有class='b'的'div'标记(是的,一些div标记带有class='a'和class='b') 为了获得这些标记,我尝试使用BS4文档()中提到的过滤函数。我的印象是find_all()

我正在抓取一个HTML网页。我正在Mac(Sierra)上使用BeautifulSoup库(4.6.0)和Python(3.7)

除此之外,我看到了一堆具有类属性的'div'标记。一些'div'标记带有多个class属性值。现在,我想根据标记名和类属性值进行筛选,例如,我想查找具有class='a'但不具有class='b'的'div'标记(是的,一些div标记带有class='a'和class='b')

为了获得这些标记,我尝试使用BS4文档()中提到的过滤函数。我的印象是find_all()将bs4标记元素传递给函数,在函数中,您可以对bs4标记元素执行任何操作。这似乎不是真的。我得到一个字符串,显然我所有的BS4标记元素操作都会引发一个异常

两个问题:

  • find_all()到底传递给函数什么?如何使用参数
  • 除了功能之外,如何才能实现所需的功能
  • 我的印象是find_all()将bs4标记元素传递给函数,在函数中,您可以对bs4标记元素执行任何操作

    你的印象是正确的。根据bs4文件(重点矿山):

    。。。定义一个函数,将元素作为其唯一参数

    因此,文档中的每个元素都被传递到filter函数,如果该函数为该元素返回
    True
    ,它将包含在
    .find_all()
    返回的元素列表中。这实际上只能作为最后的手段使用,因为它可能需要相当高的性能。我不完全确定为什么会得到字符串,一种可能是将函数传递给
    参数,该参数会传递字符串,但不能说没有看到代码

    我认为你应该做的是使用
    .find_all()
    获取所有
    类为“a”的,然后使用你自己的方法过滤这些,只包括那些没有类为“b”的,类似这样:

    divs = soup.find_all('div', class_='a')
    filtered_divs = [ div for div in divs if 'b' not in div.attrs['class'].split(' ') ]
    
    但是如果你真的想使用filter函数,它看起来就像

    class_a_not_b(e):
        if 'class' not in e.attrs: return False
        return 'a' in e.attrs['class'].split(' ') and 'b' not in e.attrs['class'].split(' ')
    
    divs = soup.find_all(class_a_not_b)
    

    到目前为止你试过什么?包括一段html和其他代码来创建一个新的应用程序,这将帮助我们了解您的具体情况。