# _*_ coding: utf-8 _*_
import os
import sqlite3
import requests
from win32.win32crypt import CryptUnprotectData
def getcookiefromchrome(host='.douban.com'):
'''最好还是从浏览器自动获取当前登录帐号的cookies,
然后再抓取内容,这里是演示从Google Chrome中获取cookies的例子。
host 登录服务器的主域名,注意要在前面加个点号。
'''
cookiepath=os.environ['LOCALAPPDATA']+r"\Google\Chrome\User Data\Default\Cookies"
sql="select host_key,name,encrypted_value from cookies where host_key='%s'" % host
with sqlite3.connect(cookiepath) as conn:
cu=conn.cursor()
cookies={name:CryptUnprotectData(encrypted_value)[1].decode() for host_key,name,encrypted_value in cu.execute(sql).fetchall()}
print(cookies)
return cookies
url='http://www.douban.com'
httphead={'User-Agent':('Mozilla/5.0 (Windows NT 6.2 WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36'),}
r=requests.get(url,headers=httphead,cookies=getcookiefromchrome('.douban.com'),allow_redirects=1)
print(r.text)
需要安装的第三方模块:requests,pywin32
其实就是检查页面某一固定的元素是否存在。
assert用得比较多,举例说明:
例如,登录成功后的界面,某个固定控件包含字符串“aaa”,找到,则证明登录成功。
assertEqual('aaa',driver.find_elements_by_class_name("android.widget.EditText").text)
assertEqual()只是其中一个方法。
断言的用法还有很多,感兴趣可以百度一下。