Python类请求多个网站

2024-04-24 16:54:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个请求函数request_url,它从不同的网站请求数据。我将此函数应用于多个不同的函数some_function_a

def some_function_a():
     url = www.facebook.com
     facebook = request_url(url)
     facebook.apply(...)  # start to do some data wrangling
     ...

def some_function_b():
     url = www.instagram.com
     instagram = request_url(url)
     instagram.apply(...)
     ...

def some_function_c():
     url = www.linkedin.com
     linkedin = request_url(url)
     linkedin.apply(...)
     ...

我想把所有的东西都打包成一个班级。不幸的是,我对python中的类不是很有经验。类的外观如何,以便我可以执行以下操作:

def some_function_a():
    facebook = request_class.facebook
    facebook.apply(...)
    ...

def some_function_b():
    instagram = request_class.instagram
    instagram.apply(...)


def some_function_c():
    linkedin = request_class.linkedin
    linkedin.apply(...)
    ...

最优雅的方式是什么?这个类的请求是什么样的


Tags: 数据函数comurlfacebook网站requestdef
2条回答

首先创建RequestClass并为其提供url属性。然后,您可以为每个站点使用不同的URL创建对象。某些函数()可以是类方法:

class RequestClass:
    def __init__(self, url):
    self.url = url

def make_request(self):
    request(self.url)

def some_function(self):
    apply(...)

要创建对象,请执行以下操作:

fb = RequestClass("www.facebook.com")

ig = RequestClass("www.instagram.com")

li = RequestClass("www.linkedin.com")

fb.make_request()
ig.make_request()
li.make_request()

如果希望访问请求中的数据,可以在请求方法中将其另存为self.data,假设向站点发出请求的方式返回数据:

class RequestClass:
    def __init__(self, url):
    self.url = url
    self.data

    def make_request(self):
        self.data = request(self.url)

要访问数据,例如,通过Facebook的请求:

fb.data #returns the data from the request to facebook

process_data(fb.data) #easily use that data in a diff function

如果在类中创建其他方法或属性,则可以轻松访问每个站点的方法或属性,例如,如果要打印请求中的数据:

fb.print_request_data()
ig.print_request_data()
li.print_request_data()

您可以这样做(您还需要正确使用请求和URL作为字符串):

class Request_class(object):
    '''
    Class with all the requests
    '''
    def __init__(self, linkedin_url):
        '''
        Constructor
        '''
        #You can pass variables to create some class properties
        #for example, if linkedin url is always the same
        self.linkedin = linkedin_url

    def facebook(self, url):
        facebook = request_url(url)
        facebook.apply(...)
        ...

    def instagram(self, url):
        instagram = request_url(url)
        instagram.apply(...)
        ...

    def linkedin(self):
        #you don't need to pass the linkedin url; it's already a class property
        linkedin = request_url(self.url)
        linkedin.apply(...)
        ...


#Then you can create an instance of the class:
my_requests = Request_class('www.linkedin.com')
#And you can call its methods:
my_requests.facebook('www.facebook.com')
my_requests.instagram('www.instagram.com')
#For this last the class already knows the url
my_requests.linkedin()

相关问题 更多 >