[Python #5] Learning Python with Selenium - Class [CN]

in #cn5 years ago (edited)

上期学了函数,这期学加长版类。
类第一行由class 类名:开头,第二行所有内容包括函数都必须缩进。
呼叫的时候先创建类对象后呼叫函数即可。

class Steemit:
   def login(self):
        ... ...
        ... ...

与java不同的是类不需要必选项。就是说你只创建函数也可以使用python,那为什么要创建类呢?
百度一下看看类到底有何用处。

探索了几个小时终于找出了几个理由,当中只抽选我这个笨脑袋可理解的几个理由。

  1. 类包含很多固定的函数,称之为魔术函数。有没有搞错?名字太。。。。 反正这类函数名前后各有两个下划线(double underscore)简称‘dunder’。其中__init__函数可以初始化类。我们可以重构此类‘dunder’函数来扩张功能。
  2. 可以与 with 关键词绑定使用。我们在处理文件的时候必须要打开,编辑,关闭文件三项来处理。但是有很多时候我们总忘掉最后‘关闭文件’这个步骤。出血大啊。with 关键词可以防止此类失误。重构魔术函数__enter__, __exit__即可与 with 连接。

那顺便把我所有的函数转换成类试试把。

Scenario

  1. Module.py 文件创建叫做 Steemit 的类和 SteemCoinpan 类
  2. 在各个类创建 login(), vote() 等函数
  3. 创建 Scenario.py 文件后,在里面创建 steemit, SteemCoinpan 对象并且把定义的 chrome driver 传到对象。
  4. 呼叫 steemit的 login() 函数, 再呼叫 SteemCoinpan的 login() 函数

image.png

image.png

Source

Module.py

from selenium import webdriver
import time
from selenium.common.exceptions import NoSuchElementException

class Steemit:

    def __init__(self, driver: webdriver) -> None:
        self.driver = driver

    def login(self):
        """
            log in to steemit
        """
        self.driver.get('https://steemit.com')
        self.driver.find_element_by_xpath('//Header/descendant::a[text()="로그인"]').click()
        self.driver.find_element_by_xpath('//input[contains(@name,"username")]').send_keys('june0620')
        with open('C:/Users/USER/Desktop/python/june0620.txt') as pw:
            for postingKey in pw:
                self.driver.find_element_by_xpath('//input[contains(@name,"password")]').send_keys(postingKey)
                self.driver.find_element_by_xpath('//button[text()="로그인"]').click()
                time.sleep(3)

    def vote(self):
        pass

    def is_post_valid(self, post: webdriver) -> bool:
        """
        Check if the post is valid
        """
        whitelist = ['xxx']
        username = post.find_element_by_xpath('descendant::span[@class="author"]/strong').text
        if username in whitelist:
            print('white List: ' + username)
            return True
        if self.is_nsfw(post):
            return False

    def is_nsfw(self, post: webdriver) -> bool:
        """
        Check if the post is nsfw.
        """
        try:
            post.find_element_by_xpath('descendant::span[text()="nsfw"]')
            return True
        except NoSuchElementException as err:
            return False

class SteemCoinpan:

    def login(self):
        """
            log in to steemcoinpan
        """
        pass

    def vote(self):
        pass

    def is_post_valid(self, post: webdriver) -> bool:
        """
        Check if the post is valid
        """
        pass

    def is_nsfw(self, post: webdriver) -> bool:
        """
        Check if the post is nsfw.
        """
        pass

Scenario.py:

from selenium import webdriver
from Module import Steemit, SteemCoinpan

# Set chromedriver
chrome = webdriver.Chrome('C:/Users/USER/Desktop/python/chromedriver/chromedriver.exe')
# Set window maximum
chrome.maximize_window()
# Create a steemit object
steemit = Steemit(chrome)
# Call function 'login'
steemit.login()
# Create a steemcoinpan object
span = SteemCoinpan(chrome)
span.login()
chrome.quit()

内容整理

Python:

  1. 在类创建函数的时候有一个惯例就是第一个参数必须为self。self和其它语言的this是同一个概念。
  2. 在同一个module可创建多个类。
  3. 命名函数的时候必须用小写且用下划线分离,命名类时用骆驼拼写法并且第一个字母用大写。不然无法区分是调用函数还是创建对象。
  4. 类初始化用 __init__ 函数。
  5. 可以链接 with 关键词处理文件。

Reference:
[Python #4] Learning Python with Selenium - Function [CN]

Sort:  

!thumbup
恭喜你!您的这篇文章入选 @justyy 今日 (2019-10-22) 榜单 【优秀的文章】, 回复本条评论24小时内领赏,点赞本评论将支持 @dailychina 并增加将来您的奖赏。
@justyy 是CN区的见证人,请支持他,给他投票,或者设置justyy为见证人代理。感谢!@justyy的主要贡献:https://steemyy.com

Congratulations! This post has been selected by @justyy as today's (2019-10-22) 【Good Posts】, Steem On! Reply to this message in 24 hours to get rewards. Upvote this comment to support the @dailychina and increase your future rewards! ^_^

SteemIt 工具、API接口、机器人和教程
SteemIt Tools, Bots, APIs and Tutorial



If you believe what I am doing, please consider a spare vote voting me here, thank you very much indeed.

@justyy - the author of https://SteemYY.com and I have been a Steem Witness for more than a year now.

@tipu curate 2

来自于 [WhereIn Android] (http://www.wherein.io)

哇😄😀 谢谢谢谢
级别真高~
!shop

Posted using Partiko Android

客气客气 我在这呢🤭
yanhan不知道怎么4级了 但3级和4级现在都一样的百分比 可能次数多点吧

Posted using Partiko Android

我也加把劲提升下级别。
tipu 给steem 注入了活力啊😀😄

Posted using Partiko Android

你好鸭,小萍萍!
@june0620赠送1枚SHOP币给你!

目前你总共有: 31枚SHOP币

查看或者交易 SHOP币 请到 steem-engine.com.

无聊吗?跟我猜拳吧! **石头,剪刀,布~**

总算让我再次见到你🤭

来自于 [WhereIn Android] (http://www.wherein.io)

Thank you so much for participating in the Partiko Delegation Plan Round 1! We really appreciate your support! As part of the delegation benefits, we just gave you a 3.00% upvote! Together, let’s change the world!

june0620,感谢你赠送SHOP币给1名用户, 你将获得来自我的33.33%点赞~
@tipu curate

Coin Marketplace

STEEM 0.20
TRX 0.14
JST 0.030
BTC 67651.30
ETH 3269.44
USDT 1.00
SBD 2.64