Selenium可以模拟正常人的浏览网页过程,所以可以绕开很多反爬机制,但这样也降低了效率,Selenium方法下需要程序识别每个按钮所对应的链接,并且进行点击,在空白填入文字,这样实现一般人的上网冲浪过程。
今天弄懂了怎么selenium模拟登录知乎,记录一下难点
-
进入知乎登录界面https://www.zhihu.com/signin?next=%2F,并打开开发者模式(按F12)
-
用最左侧按钮,点击需要解析的网页地方:
-
在对应处右键选择copy selector, 什么都不要改!:
-
先选密码登录,再输入账号密码,最后登录。
-
设置selenium来接管使用中的浏览器,先设置chrome环境变量,再在命令行中输入chrome.exe --remote-debugging-port=9222 --user-data-dir=“E:\data_info\selenium_data”
代码:
logging.basicConfig(filename = 'LoginTest.txt', level=logging.INFO, format=' %(asctime)s - %(levelname)s - %(message)s')
chrome_options = Options()
chrome_options.add_experimental_option("debuggerAddress","127.0.0.1:9222")
browser = webdriver.Chrome(options=chrome_options)
loginurl = 'https://www.zhihu.com/signin?next=%2F'
def login(driver, username, password):#重要啊,先搞定这个模拟登录
try:
logging.info("Requesting page: " + loginurl)
driver.get(loginurl)#开始登录,不用头文件,因为是selenium
except TimeoutException:
logging.info("Page load timed out but continuing anyway")
logging.info("选择密码登录")
driver.find_element_by_css_selector('div.SignFlow-tabs div:nth-child(2)').click()
logging.info("输入账号")#已经完成
inputacc = driver.find_element_by_css_selector('div.SignFlow-account div label input')
inputacc.clear()
inputacc.send_keys(str(username))
logging.info("输入密码")#不能直接输入,要切换到
driver.find_element_by_css_selector('div.SignFlow-password div label').send_keys(str(password))
#time.sleep(2)
'''
直接通过右键 copy selector!,什么都不要改!
'''
logging.info('登录')
driver.find_element_by_css_selector('#root > div > main > div > div > div > div.SignContainer-content > div > form > button').click()
#browser.close()
logging.info("Successfully logged in")