使用selenium登录微博并发送一条图文微博
selenium 是一个用于Web应用程序测试的工具。在使用python登录微博时,其登录时的密码,用户名加密有些麻烦,可以使用selenium操作浏览器登录获取cookie。
selenium安装
直接pip就可以搞定: pip install selenium
使用selenium驱动chrome浏览器需要下载chromedriver,而且chromedriver版本需要与chrome的版本对应,版本错误的话则会运行报错。
Chromedriver下载地址http://npm.taobao.org/mirrors/chromedriver/.
声明并调用浏览器对象
在这里我使用selenium操作chrom浏览器进入微博主页
from selenium import webdriver
driver = webdriver.Chrome()
driver.get('https://weibo.com/')
实现登录
在使用selenium打开网页时会有些慢,这里需要设置一个等待
import time
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
locator = (By.XPATH,'//div[@class="info_list username"]/div/input')
WebDriverWait(driver, 20, 0.5).until(EC.presence_of_element_located(locator)) # 等待用户名输入框加载完成
加载完成后输入用户名,密码完成登录