【问题标题】:What is python .get() method is doing in this scenario?在这种情况下,python .get() 方法在做什么?
【发布时间】:2017-07-27 06:58:28
【问题描述】:

我正在阅读从网页中抓取列表数据的教程,并且我们有一个名为“soup”的 BeautifulSoup 对象,我应该从“soup”中找到所有元素,这样它们就在一个表格中并且元素是在某个班级,所以他们这样做了:

> [t["class"] for t in soup.find_all("table") if t.get("class")]

所以我不明白这里有两件事,t["class"] 在这里做什么 为什么我们不简单地写 t 因为 if 条件应用在右边 为什么我们需要在里面做 t["class"]第一名。

为什么我们在这种情况下使用 .get() 方法作为布尔值,我的意思是它不返回为字典中的键存储的值?

这是否意味着美丽的汤对象是一本字典?

【问题讨论】:

    标签: python dictionary beautifulsoup


    【解决方案1】:

    "t["class"] 在这里做什么,为什么我们不简单地写 t"*

    显然是因为作者想检索标签的class属性,而不是完整的标签。

    为什么我们在这种情况下使用 .get() 方法作为布尔值,我的意思是它不返回为字典中的键存储的值?

    dict.get(key[, default=None]) 确实返回键 key 的值(如果已设置)或 default(默认为 None)如果未设置。

    这里的目标显然是只为拥有一个标签的标签获取class

    这是否意味着美丽的汤对象是一本字典?

    这里的 't' 不是“漂亮的汤对象”,它是一个 Tag 实例。虽然严格来说不是 dict,但它确实表现得像一个 wrt/html 属性。这是 FWIW 记录的。

    【讨论】:

    • 既然我们已经在做t["class"],这基本上是在检索标签的class属性,为什么我们需要在最后使用if t.get("class")
    • 对于没有 "class" 属性的标签,t['class"] 会引发 KeyError - 但由于之前已经评估了条件,它可以保护我们免受此 (t["class"] won't be executed if t.get("class ")` 返回一个虚假值)。有关获得相同结果的替代方法,请参阅 Adam Smith 的答案。
    【解决方案2】:

    dict.get 返回与其给定键关联的值,或None。举个例子:

    >>> foo = {'spam': 'eggs'}
    >>> foo.get('spam')
    'eggs'
    >>> foo['spam']
    'eggs'
    >>> foo.get('bar')
    None
    >>> foo['bar']
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    KeyError: 'bar'
    

    我对 BeautifulSoup 不熟悉,因此在这种情况下可能需要执行类似的操作,但通常您只需在添加之前检查成员身份

    [t['class'] for t in soup.find_all('table') if 'class' in t]
    

    或者很少在选择器中使用dict.get,然后过滤掉None对象

    tmp = [t.get('class') for t in soup.find_all('table')]
    result = filter(tmp, None)
    # this is equivalent to:
    # result = [v for v in tmp if v]
    

    【讨论】:

      【解决方案3】:

      是你的教程的一个例子,你可能不想得到文本,而不是类

      我会将列表理解写成“for”格式:

      result = []
      tables = soup.find_all("table")
      for t in tables:
          if t.get("class"): #Check if tables have class attribute
              result.append(t["class"]) #Probably you don't wan't the class name of the table, maybe you wan't the text
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-12-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-07
        相关资源
        最近更新 更多