异常处理

什么是异常处理 (处理异常,报错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. [Linux] 使用mount来挂载设备到目录

    一般情况下直接mount 设备路径 目录路径,就可以了.umount 设备名,就可以卸载这个设备了使用lsblk -f可以查看挂载的设备,以及这些设备的文件系统. root@tao-PC:/boot# ...

  2. 自定义安装office

    自定义安装office 1.下载office安装包:https://msdn.itellyou.cn 2.下载offiice部署工具:https://www.microsoft.com/en-us/d ...

  3. ln -s 文件夹变成文件(txt) / linux 链接出错

    问题: 平时没有注意过这这个问题,当我使用ln -s xxx yyy  将xxx 移动到yyy 路径时,文件夹就变成了txt文件, 解决: 找了半天,在stackoverflow上找到了答案,很简单, ...

  4. <Array> 277 243 244 245

    277. Find the Celebrity knows(i, j): By comparing a pair(i, j), we are able to discard one of them 1 ...

  5. Codeforces Round #552 (Div. 3) EFG(链表+set,dp,枚举公因数)

    E https://codeforces.com/contest/1154/problem/E 题意 一个大小为n(1e6)的数组\(a[i]\)(n),两个人轮流选数,先找到当前数组中最大的数然后选 ...

  6. node爬虫之图片下载

    背景:针对一些想换头像的玩家,而又不知道用什么头像的,作为一名代码爱好者,能用程序解决的,就不用程序来换头像,说干就干,然后就整理了一下. 效果图 环境配置 安装node环境 node -v node ...

  7. .NET CORE下最快比较两个文件内容是否相同的方法

    本文因为未考虑磁盘缓存, 结果不是很准确, 更严谨的结果请参看本博文的续集 最近项目有个需求,需要比较两个任意大小文件的内容是否相同,要求如下: 项目是.NET CORE,所以使用C#进行编写比较方法 ...

  8. C# 位运算基本大全

    1.原码 反码 补码 只用补码进行计算,且没有减法.只有用补码进行加法运算,具体原因,详见:http://www.cnblogs.com/zhangziqiu/archive/2011/03/30/C ...

  9. LeetCode 94:二叉树的中序遍历 Binary Tree Inorder Traversal

    题目: 给定一个二叉树,返回它的中序 遍历. Given a binary tree, return the inorder traversal of its nodes' values. 示例: 输 ...

  10. Ubuntu18.04下修改快捷键

    Ubuntu下修改快捷键 Intelij Idea在Ubuntu下的快捷键几乎和windows差不多,最常用的一个快捷键与系统冲突: Ctrl + Alt + T idea是surround with ...