【问题标题】:function missing 2 required positional arguments: 'url' and 'list'函数缺少 2 个必需的位置参数:“url”和“list”
【发布时间】:2018-06-28 10:28:15
【问题描述】:

我正在尝试编写一个 python 脚本来获取特定网页中使用的 url 数量:

TypeErrorTraceback (most recent call last)
<ipython-input-7-a3136853c4b2> in <module>()
 30     return no_use
 31 
 32 print(mining_webpage())
TypeError: mining_webpage() missing 2 required positional arguments: 'url' and 'list'

这是代码:

from bs4 import BeautifulSoup as bs 
import requests
import re
import pandas as pd
import matplotlib as plt

def mining_webpage(url,list):
   '''Finds the howmany websites are used in the webpage and counts its total number'''
    reallink=[]
    tokens=[]
    list1=[]
    no_use={}
    link=url
    word_list=list
    text=requests.get(link).text
    soup=bs(text)
    for l in soup.find_all(href=re.compile('https')):
        reallink.append(l.get('href').split('//'))
    for lists in reallink:
        '''print(lists[-1])'''
        list1.append(lists[-1].split('.'))
    '''print(list1)'''
    for l in list1:
        tokens.append(l[-2])
    for word in tokens:
        if word in no_use.keys():
            no_use[word]+=1     
        else:
            no_use[word]=1
    return no_use
print(mining_webpage())

我知道这可能有一个简单的解决方案,但我真的不知道我做错了什么,这就是我写的练习。

【问题讨论】:

标签: python beautifulsoup python-requests


【解决方案1】:

在这种情况下,错误消息本身是不言自明的:

TypeError: mining_webpage() missing 2 required positional arguments: 'url' and 'list'

您创建了一个新函数mining_webpage,它需要两个参数urllist。这意味着每次调用它时,您都需要传递两个参数。例如。

my_list = []
print(mining_webpage('http://stackoverflow.com', my_list))

或者,您可能希望重新定义mining_webpage 以便它使用更少的参数,或者如果使用比预期更少的参数调用函数,则将使用默认值。具有默认值的示例可能如下所示:

from bs4 import BeautifulSoup as bs
...
import matplotlib as plt

def mining_webpage(url='http://stackoverflow.com', list=None):
   '''Finds the howmany websites are used in the webpage and counts its total number'''
    reallink=[]
    ...

当然,以这种方式设置默认值只有在您希望经常使用的“默认”值时才有意义。

作为最后一点,list 实际上用于任何事情并不明显,我真的会避免调用任何变量list,因为它已经在 Python 标准库中定义(@987654321 @)。第二个参数似乎被用作分配新变量 word_list 的值,然后再也不会引用该变量。

【讨论】:

    猜你喜欢
    • 2013-09-27
    • 2019-02-08
    • 2021-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-13
    • 2021-07-25
    相关资源
    最近更新 更多