【发布时间】:2020-03-23 18:08:09
【问题描述】:
我正在改进我的代码,使其更易于阅读、更短且更具动态性。
我使用 dotenv 隐藏了用户名和密码。
如您所见,它首先打开一个驱动程序,然后在函数中,我要求驱动程序进入 URL,然后取决于我在参数中输入的帐户,驱动程序将访问该特定电子邮件。
我已经考虑在多个变量中分配驱动程序操作,但由于 Web 登录有 2 个步骤;
- 帐号和密码
- 加密密码
不能那样做。
有什么想法吗?
load_dotenv()
options = webdriver.ChromeOptions()
executable_path = {"executable_path": "/usr/local/bin/chromedriver"}
browser = Browser("chrome", **executable_path, headless=False)
bw = browser.driver
html = browser.html
soup = BeautifulSoup(html, "html.parser")
def open_web_email(account):
"""[This function will open web email]
Arguments:
account {[account]} -- [returns what email will open]
"""
bw.get("https://webemail.com/login")
bw.set_window_size(1080, 820)
# username = bw.find_element_by_xpath('//*[@id="username"]')
# password = bw.find_element_by_xpath('//*[@id="password"]')
# login_butt = bw.find_element_by_xpath('//*[@id="login_btn"]')
if account == "1":
time.sleep(2)
bw.find_element_by_xpath('//*[@id="username"]').send_keys(os.getenv("P_USERNAME_ONE"))
bw.find_element_by_xpath('//*[@id="password"]').send_keys(os.getenv("P_PSW_ONE"))
bw.find_element_by_xpath('//*[@id="login_btn"]').click()
bw.find_element_by_xpath('//*[@id="mailboxPassword"]').send_keys(os.getenv("P_MAILBOX_ONE"))
bw.find_element_by_xpath('//*[@id="unlock_btn"]').click()
elif account == "2":
bw.find_element_by_xpath('//*[@id="username"]').send_keys(os.getenv("P_USERNAME_TWO"))
bw.find_element_by_xpath('//*[@id="password"]').send_keys(os.getenv("P_PSW_TWO"))
bw.find_element_by_xpath('//*[@id="login_btn"]').click()
bw.find_element_by_xpath('//*[@id="mailboxPassword"]').send_keys(os.getenv("P_MAILBOX_TWO"))
bw.find_element_by_xpath('//*[@id="unlock_btn"]').click()
也许更好的方法是使用类?
【问题讨论】:
-
这似乎更适合 codereview...不确定他们的主题政策,但由于您的代码没有实际问题/错误,我不确定这是地方...
-
便捷链接:Code Review
-
谢谢!不知道这个网站的存在!
标签: python function selenium web-scraping