准备:
1、intellij idea
2、python
3、selenium
4、phantomJs
1、分析Qzone Html页面
打开手机版qzone https://mobile.qzone.qq.com
按照上面流程复制账号、密码和登录按钮的的XPath粘贴到记事本中
2、超链
1、构建浏览器并且设置请求头
2、开始请求
3、模仿用户输入
4、输入验证码
5、自动登录
6、完整代码
3、编写爬虫代码
首先创建一个浏览器对象和设置请求头
|
|
开始请求 截图
截图成功会在 project 下面生成screenshot.png
模仿用户输入 登录关键性代码
登录代码就写完了现在开始写个测试代码
运行测试结果
运行几遍后发现每次都要登录一遍,然后腾讯验证码也出来了。。。
先把验证码这块给处理了
按照开始寻找图片的方法把验证码图片、验证码输入框、按钮找出来
保存验证码
运行测试,发现以下错误
Traceback (most recent call last):
File “C:/Users/user/IdeaProjects/untitled/untitled/qzone.py”, line 108, in
browser.check_code2()
File “C:/Users/user/IdeaProjects/untitled/untitled/qzone.py”, line 67, in check_code2
que_code = self.driver.find_element_by_xpath(‘//[@id=”cap_que_img”]’)
File “D:\python\lib\site-packages\selenium\webdriver\remote\webdriver.py”, line 313, in find_element_by_xpath
return self.find_element(by=By.XPATH, value=xpath)
File “D:\python\lib\site-packages\selenium\webdriver\remote\webdriver.py”, line 791, in find_element
’value’: value})[‘value’]
File “D:\python\lib\site-packages\selenium\webdriver\remote\webdriver.py”, line 256, in execute
self.error_handler.check_response(response)
File “D:\python\lib\site-packages\selenium\webdriver\remote\errorhandler.py”, line 194, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: {“errorMessage”:”Unable to find element with xpath ‘//[@id=\”cap_que_img\”]’”,”request”:{“headers”:{“Accept”:”application/json”,”Accept-Encoding”:”identity”,”Connection”:”close”,”Content-Length”:”108”,”Content-Type”:”application/json;charset=UTF-8”,”Host”:”127.0.0.1:53613”,”User-Agent”:”Python http auth”},”httpVersion”:”1.1”,”method”:”POST”,”post”:”{\”using\”: \”xpath\”, \”value\”: \”//*[@id=\\”cap_que_img\\”]\”, \”sessionId\”: \”737e6b90-6929-11e7-8958-3b746283f061\”}”,”url”:”/element”,”urlParsed”:{“anchor”:””,”query”:””,”file”:”element”,”directory”:”/“,”path”:”/element”,”relative”:”/element”,”port”:””,”host”:””,”password”:””,”user”:””,”userInfo”:””,”authority”:””,”protocol”:””,”source”:”/element”,”queryKey”:{},”chunks”:[“element”]},”urlOriginal”:”/session/737e6b90-6929-11e7-8958-3b746283f061/element”}}
Screenshot: available via screen
说没有找到这个节点,后来分析源码发现他是包在 iframe 中的 既然包在里面了那我们切换窗口好了
|
|
手动输入验证码,暂时还不能自动输入验证码 并且也不能验证验证码是否错误或者切换
每次运行都需要手动登录太麻烦了 qzone 保存cookies 好像可以不需要手动登录了
|
|
测试代码
|
|
qzone 登录自动登录完整代码
|
|
总结
1、QQ空间登录其实可用使用js来模仿用户操作直接输入代码量也很少
2、然后这边也有一个写入cookies 的bug因为作用域不对会报错
我只是一只小菜鸟,如果你看到代码有错误的地方请提出来