本文目的:使用Selenium(一个web自动化测试的工具)模拟登录网站。
1,获取Selenium
sudo pip install -U selenium
命令行中输入来获取selenium
2,安装Chromedriver
安装chromedriver,解压后放到一个位置,不限定位置,路径记得就好
https://sites.google.com/a/chromium.org/chromedriver/downloads
3,分析网页
这里我们拿知乎来测试,打开登录界面,https://www.zhihu.com/#signin
用chrome看开发者工具
找到登录页面表单的输入框的name,用selenium的“find_element_by_name“或者你也可以用xpath来查找这个输入框。
4,代码部分
#=========selenium======================
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
driver = webdriver.Chrome('/data/chromedriver')
url = "https://www.zhihu.com/#signin"
driver.get(url)
# 查找输入框
account = driver.find_element_by_name("account")
account.clear()
account.send_keys("xxxxxx") #输入账号
pwd = driver.find_element_by_name("password")
pwd.clear()
pwd.send_keys("xxxxx") #输入密码
# 回车
account.send_keys(Keys.RETURN)
time.sleep(2)
print driver.page_source