惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

T
Tenable Blog
Last Week in AI
Last Week in AI
P
Proofpoint News Feed
Engineering at Meta
Engineering at Meta
H
Help Net Security
F
Fortinet All Blogs
MyScale Blog
MyScale Blog
宝玉的分享
宝玉的分享
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
博客园 - 司徒正美
量子位
N
Netflix TechBlog - Medium
Apple Machine Learning Research
Apple Machine Learning Research
小众软件
小众软件
Recorded Future
Recorded Future
博客园 - 三生石上(FineUI控件)
Vercel News
Vercel News
aimingoo的专栏
aimingoo的专栏
I
InfoQ
Microsoft Security Blog
Microsoft Security Blog
Scott Helme
Scott Helme
The Last Watchdog
The Last Watchdog
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
IT之家
IT之家
AI
AI
WordPress大学
WordPress大学
Security Archives - TechRepublic
Security Archives - TechRepublic
Google Online Security Blog
Google Online Security Blog
U
Unit 42
V2EX - 技术
V2EX - 技术
MongoDB | Blog
MongoDB | Blog
Schneier on Security
Schneier on Security
博客园 - Franky
H
Heimdal Security Blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Jina AI
Jina AI
W
WeLiveSecurity
P
Privacy & Cybersecurity Law Blog
Cloudbric
Cloudbric
B
Blog RSS Feed
N
News | PayPal Newsroom
S
Securelist
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
I
Intezer
Hacker News - Newest:
Hacker News - Newest: "LLM"
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
博客园_首页
罗磊的独立博客
H
Hackread – Cybersecurity News, Data Breaches, AI and More
雷峰网
雷峰网

Natalya Kosenko’s Blog

First six months of being a developer First six months of being a developer My dream to work as a developer came true My dream to work as a developer came true Enjoying Android development through pain Enjoying Android development through pain Life of a developer is not what I thought Life of a developer is not what I thought Dockerizing Next.js application Dockerizing Next.js application Little joys of engineering manager Little joys of engineering manager Failed to get freelance programmer job Failed to get freelance programmer job Study Master’s in NTU - continuation of my story Study Master’s in NTU - continuation of my story What it feels like to study Master’s in NTU Singapore What it feels like to study Master’s in NTU Singapore Writing Context Managers in Python
Writing Context Managers in Python
Natalya Kosenko · 2018-10-05 · via Natalya Kosenko’s Blog

Today was a happy day: for the first time in my life I consciously used a python context manager. When I started coding with Python in May this year, I struggled to get the idea of context managers. Then I read a book “Python Tricks” by Dan Bader, which brought me out of darkness. Since then I was waiting for some real-life situation where I can apply my new knowledge. And today it happened!

So today I was writing a web scraper that supposed to get some information from the site X. Before scraping I needed to login: fill in a form and submit it, that is why I decided to use Selenium Webdriver. My first impulse was to write something like this:

driver = webdriver.Chrome()
try:
    driver.get('http://www.natalyakosenko.com/')

    email = driver.find_element_by_name('email')
    password = driver.find_element_by_name('password')

    email.send_keys('my_email')
    password.send_keys('my_password')
    driver.find_element_by_name('submit').click()
finally:
    driver.close()

Basically, this code creates an instance of Chrome webdriver, then tries to do some stuff (in this case fills in email/password and presses Submit button), and finally close method is called to close a browser.

Then I realised that I will need to use Selenium Webdirver in other parts of my code, and I did not want to instantiate driver and write try/catch again and again. And this is where I thought: what a great opportunity to try a with statement in action!

The previous code written using with statement:

class SeleniumDriver:
    def __enter__(self):
        self.driver = webdriver.Chrome()
        return self.driver

    def __exit__(self, exc_type, exc_val, exc_tb):
        if self.driver:
            self.driver.close()


with SeleniumDriver() as driver:
    driver.get('http://www.natalyakosenko.com/')

    email = driver.find_element_by_name('email')
    password = driver.find_element_by_name('password')

    email.send_keys('my_email')
    password.send_keys('my_password')
    driver.find_element_by_name('submit').click()

What is the benefit, you might think, instead of 12 lines of code got 19. But I do not need to define SeleniumDriver class every time. Whenever I need to use Selenium Webdriver in other parts of the code, I can simply write this:

with SeleniumDriver() as driver:
    driver.get('http://www.natalyakosenko.com/')

    email = driver.find_element_by_name('email')
    password = driver.find_element_by_name('password')

    email.send_keys('my_email')
    password.send_keys('my_password')
    driver.find_element_by_name('submit').click()

Isn’t it beautiful?