异常处理

什么是异常处理 (处理异常,报错error)

print(1 / 0)  # 报了0除错误

# 打印结果:
Traceback (most recent call last):
File "D:/pycharm_project/day07/01异常处理.py", line 18, in <module>
print(1 / 0)
ZeroDivisionError: division by zero

捕捉异常

try:
print(1 / 0) # 有错误就跳过,没错误就执行
except ZeroDivisionError: # 错误被捕捉了
pass # 啥也不做
print(1)

这种方法只能捕捉这个指定错误, 当然也有其他错误

try:
print(x)
print(1 / 0) # 有错误就跳过,没错误就执行
except ZeroDivisionError: # 错误被捕捉了
pass # 啥也不做
except NameError:
pass
print(1)

这样很麻烦,异常有很多种

try:
print('--------')
print(a)
except Exception as e: # 把错误信息输入出来,同时一般把错误信息记录到日志
print(e) print('--------') # 打印结果:
--------
name 'a' is not defined
--------

这样就用Exception 就能自动识别错误,很方便~

字符串常用方法

索引取值

s = 'hello'
print(s[0]) # 取到h

切片

s = 'hello world'
print(s[0:5]) # 取到hello

成员运算

s = 'hello'
print('h' in s) # 打印True

for循环

s = 'hello'
for i in s:
print(i) # 打印:
h
e
l
l
o

字符串长度

s = 'hello'
print(len(s)) # 打印字符串长度 5

strip()

s = '** hello  '
print(s.strip()) # 默认去掉两端空格
print(s.strip('*')) # 去掉*
print(s.strip('* h')) # 去掉* h

l.strip() 和 r.strip()

s = '**cwz**'
print(s.lstrip('*')) # 去掉左边*
print(s.rstrip('*')) # 去掉右边*

startswith()和endswith()

s = 'hello'
print(s.startswith('h')) # True
print(s.endswith('o')) # True

find() 寻找索引位置

s = 'hello'
print(s.find('h')) # 打印0
print(s.find('x')) # 字符串中没有的返回-1
print(s.find('l')) # 字符串中有相同的,找第一个 返回2

index() 索引位置

s = 'hello'
print(s.index('o')) # 打印4
print(s.index('a')) # 字符串中没有的直接报错

join() 把列表中元素拼接起来

lt = ['a','b','c']
print('*'.join(lt)) # 打印结果:
a*b*c

split() 切割

s = 'a*b*c'
print(s.split('*')) # 以*切割 # 打印结果:
['a', 'b', 'c']

replace 替换

s = 'reese neo'
print(s.replace('reese','cwz')) # 打印结果:
cwz neo

center/ljust/rjust 居中/居左/居右

s = 'hello'
print(s.center(20,'-'))
print(s.ljust(20,'-'))
print(s.rjust(20,'-')) # 打印结果:
-------hello--------
hello---------------
---------------hello

isdigit() 和 isalpha()

s = '123'
print(s.isdigit()) # 判断是否全为数字 True
print(s.isalpha()) # 判断是否全为字母 Flase

count 计数

s = 'aabcda'
print(s.count('a')) # 打印3

selenium模块

什么是selenium

selenium是一个自动化测试工具

为什么要用selenium

  • 通过selenium可以驱动浏览器,跳过登录滑动验证
  • 缺点是爬虫效率低下

怎么使用selenium

selenium基本使用

from selenium import webdriver  # 用来驱动浏览器
import time # webdriver.Chrome('驱动绝对路径')
driver = webdriver.Chrome(r'E:\chromedriver_win32\chromedriver.exe')
driver.get('https://www.baidu.com') time.sleep(10) # 等待10s driver.close() # 关闭驱动

selenium驱动浏览器输入

from selenium import webdriver
import time try:
driver = webdriver.Chrome(r'E:\chromedriver_win32\chromedriver.exe')
driver.get('https://www.baidu.com') # 打开百度 # 通过id查找输入框
input_tag = driver.find_element_by_id('kw')
input_tag.send_keys('四驱车') # 输入查找内容 # 通过id查找百度一下按钮
submit_button = driver.find_element_by_id('kw')
submit_button.click() # 点击百度一下按钮 time.sleep(10) finally: # 无论有没有异常,都会执行下面的代码,关闭驱动
driver.close() # 关闭驱动

selenium模拟登录

from selenium import webdriver
import time
from selenium.webdriver.common.keys import Keys # 键盘按键操作 driver = webdriver.Chrome(r'E:\chromedriver_win32\chromedriver.exe') try:
driver.implicitly_wait(10) # 等待浏览器加载数据10s
driver.get('https://leetcode-cn.com/') # 通过文本查找登录按钮
login_button = driver.find_element_by_link_text('登录')
login_button.click() # 通过class查找用户名输入框
username = driver.find_element_by_class_name('css-paawy7-BasicInput')
username.send_keys('123456789@qq.com') # 通过name查找密码输入框
password = driver.find_element_by_name('password')
password.send_keys('123456') password.send_keys(Keys.ENTER) # 直接按回车 time.sleep(10) finally:
driver.close()

selenium爬取京东商品信息

from selenium import webdriver
import time
from selenium.webdriver.common.keys import Keys # 键盘按键操作 driver = webdriver.Chrome(r'E:\chromedriver_win32\chromedriver.exe') try:
driver.implicitly_wait(10) # 等待浏览器加载数据10s
driver.get('https://www.jd.com/') # 通过id号查找输入框
goods_input = driver.find_element_by_id('key')
goods_input.send_keys('笔记本电脑')
# 操纵键盘 按回车键
goods_input.send_keys(Keys.ENTER) # 直接按回车搜索
time.sleep(3) # 等待数据加载完成 # 通过id查找所有商品的父标签
goods_div = driver.find_element_by_id('J_goodsList')
# 通过class 标签查找goods_div下的所有li标签
goods_list = goods_div.find_elements_by_class_name('gl-item')
# print(goods_list) # 循环 获取li标签
for goods in goods_list:
# 获取商品价格文本
# goods_price = goods.find_element_by_link_text('p-price').text
# css属性选择器
goods_price = goods.find_element_by_css_selector('.p-price i').text
goods_name = goods.find_element_by_css_selector('.p-name em').text
goods_commit = goods.find_element_by_css_selector('.p-commit a').text
goods_url = goods.find_element_by_css_selector('.p-name a').get_attribute('href') goods_data = f'''
商品名称:{goods_name}
商品价格:{goods_price}
评价人数:{goods_commit}
详情链接:{goods_url}
'''
with open('笔记本电脑.txt', 'a', encoding='utf8') as f:
f.write(goods_data) time.sleep(10) finally:
driver.close()

异常处理,常用字符串方法,selenium模块的更多相关文章

  1. Python学习之==>常用字符串方法

    1.常用字符串方法 a = '\n 字 符 串 \n\n' b = a.strip() # 默认去掉字符串两边的空格和换行符 c = a.lstrip() # 默认去掉字符串左边的空格和换行符 d = ...

  2. 48-python基础-python3-字符串-常用字符串方法(六)-strip()-rstrip()-lstrip()

    7-用 strip().rstrip()和 lstrip()删除空白字符 strip()字符串方法将返回一个新的字符串,它的开头或末尾都没有空白字符. lstrip()和 rstrip()方法将相应删 ...

  3. 47-python基础-python3-字符串-常用字符串方法(五)-rjust()-ljust()-center()

    6-rjust().ljust()和 center()方法对齐文本 rjust()和 ljust()字符串方法返回调用它们的字符串的填充版本,默认通过插入空格来对齐文本. rjust()和 ljust ...

  4. 44-python基础-python3-字符串-常用字符串方法(二)-isalpha()-isalnum()-isdigit()-isspace()-istitle()

    3-isX 字符串方法   序号 方法 条件 返回结果1 返回结果2 1 isalpha() 如果字符串只包含字母,并且非空; True False 2 isalnum() 如果字符串只包含字母和数字 ...

  5. 43-python基础-python3-字符串-常用字符串方法(一)-upper()-lower()-isupper()-islower()

    请注意, 这些方法没有改变字符串本身,而是返回一个新字符串. 如果你希望改变原来的字符串,就必须在该字符串上调用 upper()或 lower(),然后将这个新字符串赋给保存原来字符串的变量.   1 ...

  6. 【java】开发中常用字符串方法

    java字符串的功能可以说非常强大, 它的每一种方法也都很有用. java字符串中常用的有两种字符串类, 分别是String类和StringBuffer类. Sting类 String类的对象是不可变 ...

  7. 第1章 Java中常用字符串方法总结

    1.1 charAt方法——提取指定字符 1.2 codePointAt方法——提取索引字符代码点 1.3 codePointBefore方法——获取索引前一个字符的代码点 1.4 codePoint ...

  8. JavaScript基础进阶之常用字符串方法总结

    前面三篇文章简单的把JavaScript基础内容过了一遍,我们已经可以用JavaScript写一些简单的代码了. 今天主要总结一下JavaScript中String对象中自带的一些方法,来帮助我们处理 ...

  9. JavaSctipt 常用字符串 方法及使用方式

    1. charAt(x) charAt(x)返回字符串中x位置的字符,下标从 0 开始. //charAt(x) var myString = 'jQuery FTW!!!'; console.log ...

随机推荐

  1. [Go] gocron源码阅读-go语言web框架Macaron

    gocron源码中使用的是马卡龙框架,下面这个就是安装这个框架,和一般的MVC框架很像go get gopkg.in/macaron.v1git clone https://github.com/go ...

  2. [Linux]gocron定时任务平台的部署

    采用二进制文件的方式部署非常简单,因为go已经把源码打包成了可执行文件,下载下来直接运行就可以了,不需要自己去编译和配置依赖 下载执行文件的地址是:https://github.com/ouqiang ...

  3. Node.js—概述

    一.Node.js与其他语言对比   Node.js不是一种独立的语言,与PHP.JSP.Python.Perl.Ruby的"既是语言,也是平台"不同,Node.js的使用Java ...

  4. 浅谈JS递归

    简单理解就是函数内部不断调用自身 直接上代码: function dg(num){ ){ ; }else{ ) } } console.log(dg()) 最后输出值为21,记住加限制条件退出递归,不 ...

  5. js 三种存储方式的区别

    javaScript有三种数据存储方式,分别是: sessionStorage localStorage cookie 相同点:都保存在浏览器端,同源的 不同点: ①传递方式不同 cookie数据始终 ...

  6. CF343D Water Tree 树链剖分

    问题描述 LG-CF343D 题解 树剖,线段树维护0-1序列 yzhang:用珂朵莉树维护多好 \(\mathrm{Code}\) #include<bits/stdc++.h> usi ...

  7. 其它 用VB6创建ActiveX.dll

    1.打开VB6 2.选择 ActiveX DLL,点击打开 3.在窗口输入测试代码 Public Function addstr(str As String) As String addstr = & ...

  8. Debug 路漫漫-12:Python: ValueError: 'userid' is both an index level and a column label, which is ambiguous.

    啊,又遇到难题了 == 想要对两个 dataframe 做自然连接 merge,连接的key 为 “userid”,但是报错:ValueError: 'userid' is both an index ...

  9. 云原生生态周报 Vol. 15 | K8s 安全审计报告发布

    业界要闻 CNCF 公布 Kubernetes 的安全审计报告 报告收集了社区对 Kubernetes.CoreDNS.Envoy.Prometheus 等项目的安全问题反馈,包含从一般弱点到关键漏洞 ...

  10. Redis学习记录及Jedis代码示例

    文章目录 二.Redis简介 三.Redis安装 1. 下载并解压安装 2. 安装C语言编译环境 3. 修改安装位置 4. 编译安装 5.启动Redis服务器 ①默认启动 ②定制配置项启动 [1]准备 ...