三元运算符
if 条件成立,if前面的结果赋值给to,否则else后面的内容赋值给to
to = 'en' if lan=='zh' else 'zh'
requests进行携带cookie登录
- cookie字符串放在headers中
- 把cookie字典交给requests请求方法的cookies
字典推导式
{i:i+10 for i in range(10) if i%2==0}
寻找登录接口的方法
- form表单action对应的url地址
- 用户名和密码的input标签中,name的值作为键,用户名和密码作为值的字典,作为post_data
- 通过抓包,定位url地址
- form data
分析 js,获取加密的数据
- 观察变化
- 定位js
- 从 event listener中寻找
- search all file中寻找关键字
- 进行分析
- 通过添加断点的方式分析js
- 执行js
- 完全的使用python模拟js的执行过程
requets处理ssl证书
requests.get(url, verify=False)
url地址解码的方法
requests.utils.unquote(url)
获取响应中的cookie,转化为字典
response = requests.get(url, headers=headers)
requests.utils.dict_from_cookiejar(response.cookies)
超时参数的使用
requests.get(url, timeout=3) # 超时时间为3秒
retrying模块的使用
- from retrying import retry
- 通过装饰器的方法使用retry,进行异常捕获,重新执行被装饰的函数
from retrying import retry
@retry(stop_max_attempt_number=3)
def fun():
pass
爬虫中数据的分类
- 结构化数据,json、xml
- 使用模块转换为python类型
- 非结构化数据, html
- re.xpath
json是什么以及如何使用
json的概念
- json是一种轻量的数据交换格式,适用于进行数据交互
找到json返回的url
-
确定数据的位置
- 在url对应的响应中搜索关键字
- 在preview中搜索关键字
-
切换手机版寻找
- 当电脑版找不到json时,可以尝试切换为手机版
- 当使用json的url地址请求不到数据的时候可以在电脑版再请求一遍,查看request headers 有什么不同,然后把不同的参数添加到python的headers中
-
json.loads(json_str) json字符串转化为python类型
-
json.dumps(python_type, ensure_ascii=False) python类型转化为json字符串
-
json.load() 把包含json的类文件对象中的数据提取出来转化为python类型
-
json.dump() python类型存入类文件对象中
正则的语法
-
. # 匹配除了\n外的所有字符 re.findall("a.c","abc") Out[3]: ['abc'] re.findall("a.c",'a\nc') Out[4]: [] # 要想匹配所有字符可以使用,re.DOTALL 或 re.S re.findall('a.c','a\nc',re.DOTALL) Out[5]: ['a\nc'] re.findall('a.c','a\nc',re.S) Out[7]: ['a\nc']
-
[] # 匹配括号里的任意字符一次 re.findall('a[bcd]e','abe') Out[11]: ['abe'] re.findall('a[bcd]e','abce') Out[12]: [] # 想要匹配尽可能多,需要使用[]+ re.findall('a[bcd]+e','abce') Out[13]: ['abce']
-
在爬虫中,使用“|”可以在数据清洗时将不想要的换行符以及其他字符替换为空白
# | 的使用 re.findall('ab|ce','abce') Out[15]: ['ab', 'ce']
-
常见的正则字符
- \d 匹配数字[0-9]
- \D 匹配非数字
- \s 匹配空白字符[<空格>\t\r\n]
- \S 匹配非空白字符
- \w 匹配单词字符
- \W 匹配非单词字符