如何访问类实例的属性

时间:2016-01-24 16:47:55

标签: python class

我正在尝试访问在另一个类中定义的类实例的属性,但我不断收到错误,指出没有属性'get'。

from selenium import webdriver

class Driver:
    proxy = [1, 2, 4]

    def get_driver(self):
        driver = webdriver.Firefox()
        if self.proxy[0] == 1:
            return self

driver = Driver()
driver.get_driver()
driver.get("https://www.youtube.com/watch?v=5xxQs34UMx4&index=101&list=PLihUZHHwjm2GtO_ikMyDg7ot1ENmmYodL")
print driver.proxy

4 个答案:

答案 0 :(得分:0)

您的Driver课程可能应该被称为DriverFactory或类似的东西。那么你的代码看起来会更具可读性:

class DriverFactory(object):
    proxy = [1, 2, 4]

    def get_driver(self):
        driver = webdriver.Firefox()
        if self.proxy[0] == 1:
            return driver
        return None

driver_factory = DriverFactory()
driver = driver_factory.get_driver()
driver.get("https://www.youtube.com/.....")
print driver_factory.proxy

但是仍然没有理解self.proxy部分应该做什么,以及为什么返回自己的东西存在于原始代码中?

答案 1 :(得分:0)

我可以想到几种访问实例属性的方法

  1. dir(obj)
  2. obj.__dict__
  3. 使用ipython的自动填充功能 - 在交互式shell中输入obj 标签

答案 2 :(得分:0)

我将尝试专注于基础知识 - 您可以根据您的需求进行调整。我认为您希望使用python在selenium驱动程序中自动执行代理选择,您可以尝试如下 -

import random
from selenium import webdriver
from selenium.webdriver.common.proxy import *

proxies = ["76.9.5.82:65335","45.55.179.51:80","192.99.38.42:35997","40.76.212.171:80","128.136.162.223:3128","104.238.138.253:80","163.153.8.130:1080","208.67.1.154:80","107.151.152.218:80","23.253.208.241:80","104.42.229.65:3128","23.239.134.14:80","46.231.133.106:80","97.77.104.22:80","54.68.135.82:80","178.62.247.158:3128","80.82.64.30:3128","107.151.152.210:80","92.222.93.240:8888","78.46.243.54:3128","69.36.65.214:1080","51.255.192.42:3128","159.122.253.8:3128","51.255.50.106:3128","207.91.10.234:8080","5.45.73.218:80","52.27.22.139:3128","45.63.69.40:8080","206.222.24.100:8080","163.44.119.72:8080"]
def my_proxy(PROXY_HOST,PROXY_PORT):
    fp = webdriver.FirefoxProfile()
    # Direct = 0, Manual = 1, PAC = 2, AUTODETECT = 4, SYSTEM = 5
    print PROXY_PORT
    print PROXY_HOST
    fp.set_preference("network.proxy.type", 1)
    fp.set_preference("network.proxy.http",PROXY_HOST)
    fp.set_preference("network.proxy.http_port",int(PROXY_PORT))
    fp.set_preference("general.useragent.override","Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/4")
    fp.update_preferences()
    return webdriver.Firefox(firefox_profile=fp)


driver  = my_proxy(*random.choice(proxies).split(':'))
driver.get('https://www.google.com.bd/?gws_rd=cr,ssl&ei=AAOlVoeHM4OtuQT84px4')
print driver.page_source.encode('utf-8')

致谢:我借了一些代码。

答案 3 :(得分:-1)

您正在应用驱动程序实例上的.get。尝试改为 -

    my_driver = driver.get_driver()
    my_driver.get("https://www.youtube.com/watchv=5xxQs34UMx4&index=101&list=PLihUZHHjm2GtO_ikMyDg7ot1ENmmYodL")
    print driver.proxy`