我该如何解决“缺少1个必需的位置参数”

时间:2018-11-23 05:56:10

标签: python methods typeerror

我在课堂上写了一个方法,并遇到以下错误

yearLinks = link(root_url + '/oilmarketreport/reports/')
TypeError: link() missing 1 required positional argument: 'url'

我的代码是:-

class Data:
    def __init__(self):
        try: ------
             ----
        else:

 def link(self, url):

        all_links = []
        page = requests.get(url)
        soup = BeautifulSoup(page.text, 'html.parser')
        for href in soup.find_all(class_='omrlist'):
            all_links.append(root_url + href.find('a').get('href'))
        return all_links
 yearLinks = link(root_url + '/oilmarketreport/reports/')
 reportLinks = []
 for url in yearLinks:
     links = link(url)

那么我如何在python中解决这个问题。

3 个答案:

答案 0 :(得分:1)

您必须执行self.link(url)。它缺少self参数。 编辑:

您可以将行更新为:

yearLinks = self.link(root_url + '/oilmarketreport/reports/')

答案 1 :(得分:0)

这是一个不清楚的问题。也许staticmethod是您想要的。

class Data:
    def __init__(self):
        try: ------
             ----
        else:
 @staticmethod
 def link(url):

        all_links = []
        page = requests.get(url)
        soup = BeautifulSoup(page.text, 'html.parser')
        for href in soup.find_all(class_='omrlist'):
            all_links.append(root_url + href.find('a').get('href'))
        return all_links
 yearLinks = Data.link(root_url + '/oilmarketreport/reports/')
 reportLinks = []
 for url in yearLinks:
     links = Data.link(url)

答案 2 :(得分:0)

为清楚起见:

class Data:
    def __init__(self):
       """"""

    @staticmethod
    def link(url):
        return url


print(Data.link("some_link"))    # call method of class Data (will print "some_link")