180-爬虫3-自动操作浏览器工具selenium模块的使用
今日内容
1 项目演示-mkvirtualenv -p python3 gist-git clone xxx-pycharm打开-确保python解释器3.6(如果是3.6以上,百度改源码)-修改配置文件连接数据库使用sqlite-创建一个超级用户,把别人密码全改成自己-查看项目流程及代码2 bs4模块,html解析,(解析json,使用json模块)-在浏览器中看到的数据,会比使用requests模块拿回来的数据多(requests模块不能主动发送ajax请求,渲染页面---》request-html)3 bs4 使用-遍历文档树-soup.body.p-取属性 soup.body.p.attrs 或者 soup.body.p['name']-取文本soup.body.p.text 把子子孙孙的文本拼到一起-取文本soup.body.p.string 只取当前p标签的文本,如果还有子标签,取出None-取文本soup.body.p.strings 取出子子孙孙标签的文本,放到一个生成器中
昨日回顾
1 bs4 遍历文档树
'''
#遍历文档树:即直接通过标签名字选择,特点是选择速度快,但如果存在多个相同的标签则只返回第一个
#1、用法
#2、获取标签的名称
#3、获取标签的属性
#4、获取标签的内容
#5、嵌套选择
#6、子节点、子孙节点
#7、父节点、祖先节点
#8、兄弟节点
'''from bs4 import BeautifulSoup
html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title" id='id_pp' name='lqz'>asdfasdf<b>asdfas</b><span>span<b>bbb</b></span></p><p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p><p class="story">...</p>
"""soup=BeautifulSoup(html_doc,'lxml')# 遍历文档树(速度快)
#6、子节点、子孙节点
# print(soup.p.contents) #p下所有子节点
# print(soup.p.children) #得到一个迭代器,包含p下所有子节点
# print(list(soup.p.children)) #得到一个迭代器,包含p下所有子节点
#
# for i,child in enumerate(soup.p.children):
# print(i,child)
#
# print(soup.p.descendants) #获取子孙节点,p下所有的标签都会选择出来
# for i,child in enumerate(soup.p.descendants):
# print(i,child)
#7、父节点、祖先节点# print(soup.a.parent) #获取a标签的父节点# print(soup.a.parents) #找到a标签所有的祖先节点,父亲的父亲,父亲的父亲的父亲...
# print(list(soup.a.parents)) #找到a标签所有的祖先节点,父亲的父亲,父亲的父亲的父亲...#8、兄弟节点
# print(soup.a.next_sibling) #下一个兄弟
# print(soup.a.previous_sibling) #上一个兄弟
#
# print(list(soup.a.next_siblings)) #下面的兄弟们=>生成器对象
# print(list(soup.a.previous_siblings)) #上面的兄弟们=>生成器对象
2 bs4的搜索文档树
from bs4 import BeautifulSoup
html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title" id='id_pp' name='lqz'>asdfasdf<b>asdfas</b><span>span<b>bbb</b></span></p><p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>
<a href="http://example.com/lacie" class="sister1" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p><p class="story">...</p>
"""soup=BeautifulSoup(html_doc,'lxml')# find和find_all的用法:用法完全一样,只不过find找到第一个,find_all找到所有# 5种过滤器:字符串、正则表达式、列表、True、方法# 字符串:name:标签名 class_:类名 id:id号 href:href
# 只要是BeautifulSoup对象Tag的对象,可以继续find,继续遍历 . 找
# res=soup.find(name='body').p
# res=soup.find(name='body').find(name='p')
# print(type(res))
# print(res)# res=soup.body.find(id='link2')
# res=soup.body.find(href='http://example.com/lacie')
# res=soup.body.find(name='a',href='http://example.com/lacie')
# print(res)# 列表# res=soup.find_all(name=['a','p'])
# res=soup.find_all(id=['link2','link3'],class_='sister')
# print(res)# 正则表达式
# import re
# # res=soup.find_all(name=re.compile('^b'))
# res=soup.find_all(class_=re.compile('^s'),name='a')
# print(res)# True
# res=soup.find_all(name=True)
# res=soup.find_all(class_=True)
# res=soup.find_all(id=True)# res=soup.find_all(href=True)
# for i in res:
# url=i['href']
# print(url)# print(res)# 方法(了解)
# def aaa(tag):
# # return tag.has_attr('class') and not tag.has_attr('id')
# return tag.has_attr('class') and tag.has_attr('id')
#
# res=soup.find_all(name=aaa)
# print(res)
4 find_all的其它参数
# find的其它参数
#attrs
# res=soup.find_all(attrs={'id':'link1'})
# res=soup.find_all(id='link1')# recursive 是否递归查找,只找一层
# res=soup.body.find_all(id='bb',recursive=False)
# res=soup.body.find_all(id='bb')# text 文本内容(5种过滤器)
# res=soup.body.find_all(text='asdfas')[0].parent# limit
# res=soup.body.find_all(True)
res=soup.body.find_all(name=True,limit=1)soup.find()
print(res)
4 css选择器
# css选择器'''#id_p :#id号
.class1 :.类名
body :标签名
p>b :p的亲儿子b
p b :p的的后代b'''
# select写css选择器 通用的(bs4,selenium,lxml)
# res=soup.select('body>p')
# res=soup.select('body p')
# res=soup.select('#link1')
# print(res)# css选择器可以之间copy
# #maincontent > h1
## 2、获取属性
# print(soup.select('#link1')[0].attrs)
# # print(type(soup.select('#link1')[0]))
# print(soup.select('#link1')[0].text)# 3、获取内容
# print(soup.select('#list-2 h1')[0].get_text())
5 selenium的介绍
1 自动化测试工具,控制浏览器,模拟人的行为,做爬虫为了解决使用requests模块无法执行ajax获取数据
2 使用selenium+半人工登录,获取cookie-----》给requests模块使用
6 selenium的使用
1 安装模块 pip3 install selenium
2 驱动浏览器(需要浏览器驱动---》不同去不同浏览器官网下载),下载的驱动要跟浏览器版本对应http://npm.taobao.org/mirrors/chromedriver/https://sites.google.com/a/chromium.org/chromedriver/downloads
3 chrom浏览器为例
# 模块装完了
# 下一个谷歌浏览器驱动,放到项目根路径下# 开始使用from selenium import webdriver
# import time
# # 拿到一个谷歌浏览器对象
# # 打开谷歌浏览器(指定驱动在哪)
# bro=webdriver.Chrome(executable_path='chromedriver.exe')
# # 在地址栏输入http://www.baidu.com
# bro.get('http://www.cnblogs.com')
#
# print(bro.page_source) # 该页面的源代码
# time.sleep(5)
# # 关闭浏览器
# bro.close()# 无界面浏览器# import time
# from selenium.webdriver.chrome.options import Options
# chrome_options = Options()
# chrome_options.add_argument('window-size=1920x3000') #指定浏览器分辨率
# chrome_options.add_argument('--disable-gpu') #谷歌文档提到需要加上这个属性来规避bug
# chrome_options.add_argument('--hide-scrollbars') #隐藏滚动条, 应对一些特殊页面
# chrome_options.add_argument('blink-settings=imagesEnabled=false') #不加载图片, 提升速度
#
# # 隐藏浏览器界面
# chrome_options.add_argument('--headless') #浏览器不提供可视化页面. linux下如果系统不支持可视化不加这条会启动失败
#
# bro=webdriver.Chrome(executable_path='chromedriver.exe',options=chrome_options)
# bro.get('http://www.cnblogs.com')
#
# print(bro.page_source)
# time.sleep(5)
# # 关闭浏览器
# bro.close()
7 模拟登录百度
from selenium import webdriverimport timebro=webdriver.Chrome(executable_path='chromedriver.exe')bro.get('http://www.baidu.com')bro.implicitly_wait(100) # 如果控件没有加载出来,会等一会# 根据a标签链接的文字来查找
login_a=bro.find_element_by_link_text('登录')
# 点击一下
login_a.click()# 用户名登录的p标签,使用id找username_login_p=bro.find_element_by_id('TANGRAM__PSP_11__footerULoginBtn')
username_login_p.click()# username_input=bro.find_element_by_id('TANGRAM__PSP_11__userName')
username_input=bro.find_element_by_name('userName')
# 写入用户名
username_input.send_keys('306334678@qq.com')password_input=bro.find_element_by_id('TANGRAM__PSP_11__password')
password_input.send_keys('sss')login_button=bro.find_element_by_id('TANGRAM__PSP_11__submit')time.sleep(5)
login_button.click()time.sleep(10)print(bro.get_cookies())bro.close()
8 selenium的其它使用
import time
from selenium import webdriverbro=webdriver.Chrome(executable_path='chromedriver.exe')
# bro.get('http://www.baidu.com')# print(bro.page_source)# 选择器
# 1、find_element_by_id 通过id获取控件
# 2、find_element_by_link_text 通过a标签的文本获取标签
# 3、find_element_by_partial_link_text 通过a标签的文本模糊匹配获取标签
# 4、find_element_by_tag_name 通过标签名找
# 5、find_element_by_class_name 通过类名找
# 6、find_element_by_name 通过name属性找
# 7、find_element_by_css_selector css选择器
# 8、find_element_by_xpath xpath选择器# input_1=bro.find_element_by_css_selector('#kw')
# # 往输入框中写文字
# input_1.send_keys('美女')
#
# search_btn=bro.find_element_by_css_selector('#su')
# search_btn.click()# 获取某个标签的属性,位置,id,名字..# input_1=bro.find_element_by_css_selector('#kw')
# print(input_1.id)
# print(input_1.tag_name)
# print(input_1.get_attribute('maxlength'))
# print(input_1.location)
# print(input_1.size)## 等待元素被加载(显示等待,隐士等待)
# bro.implicitly_wait(10) # 隐士等待,等待所有,再下方再去找一个控件,如果控件没有加载出来,最多等待10s# 显示等待(基本不用),指定等待某个控件几秒
# from selenium.webdriver.support.wait import WebDriverWait
# from selenium.webdriver.support import expected_conditions as EC
# from selenium.webdriver.common.by import By #按照什么方式查找,By.ID,By.CSS_SELECTOR
# wait=WebDriverWait(bro,10)
# wait.until(EC.presence_of_element_located((By.ID,'kw')))## 控件其它操作
# 点击操作
# search_btn=bro.find_element_by_css_selector('#su')
# search_btn.click() # 点击操作# input_1=bro.find_element_by_css_selector('#kw')
# # 往输入框中写文字
# # 清空操作
# input_1.send_keys('美女')
# time.sleep(1)
# input_1.clear()
# input_1.send_keys('帅哥')### 执行js
# bro.get('https://www.pearvideo.com/video_1715923')
# bro.execute_script('alert(urlMap.registerUrl)')# bro.execute_script('scroll(0,30000)') # 滑倒屏幕底部,有的页面滑倒底部自动加载数据# 模拟浏览器前进后退#
# bro.get('http://www.baidu.com')
# bro.get('http://www.taobao.com')
# bro.get('http://www.cnblogs.com')
#
# bro.back()
#
# time.sleep(1)
# bro.forward()
# time.sleep(1)# bro.get('http://www.cnblogs.com')
#
# time.sleep(30)### cookie的处理
# print(type(bro.get_cookies())) # 把所有cookie取出来
# cookies=bro.get_cookies()
# import json
# with open('cookie.json','w') as f:
# json.dump(cookies,f)
#
# # 取到cookie之后,存到文件中
# # 再打开一个页面,还是这个网站,把cookie之间写入
#
# time.sleep(1)
# # 关闭浏览器
# bro.close()### 选项卡管理
# browser=webdriver.Chrome()
# browser.get('https://www.baidu.com')
# browser.execute_script('window.open()')
#
# print(browser.window_handles) #获取所有的选项卡
# browser.switch_to_window(browser.window_handles[1])
# browser.get('https://www.taobao.com')
# time.sleep(2)
# browser.switch_to_window(browser.window_handles[0])
# browser.get('https://www.sina.com.cn')
# browser.close()## 异常捕获
try:browser=webdriver.Chrome()browser.get('http://www.runoob.com/try/try.php?filename=jqueryui-api-droppable')browser.switch_to.frame('iframssseResult')except Exception as e:print(e)
finally:browser.close() # 关闭浏览器# 动作链
# 使用selenium爬取京东商品信息
from selenium import webdriver
import json
import time
bro=webdriver.Chrome(executable_path='chromedriver.exe')
bro.get('http://www.cnblogs.com')
with open('cookie.json','r') as f:cookie=json.load(f)for i in cookie:bro.add_cookie(i)
time.sleep(1)
bro.refresh()
time.sleep(1)
bro.refresh()time.sleep(4)
bro.close()
180-爬虫3-自动操作浏览器工具selenium模块的使用相关推荐
- 从入门到入土:Python爬虫学习|Selenium自动化模块学习|简单入门|轻松上手|自动操作浏览器进行处理|chrome|PART01
此博客仅用于记录个人学习进度,学识浅薄,若有错误观点欢迎评论区指出.欢迎各位前来交流.(部分材料来源网络,若有侵权,立即删除) 本人博客所有文章纯属学习之用,不涉及商业利益.不合适引用,自当删除! 若 ...
- python 全栈开发,Day136(爬虫系列之第3章-Selenium模块)
python 全栈开发,Day136(爬虫系列之第3章-Selenium模块) 一.Selenium 简介 selenium最初是一个自动化测试工具,而爬虫中使用它主要是为了解决requests无法直 ...
- 更为简单的Ctrl+S自动刷新浏览器工具-LinrF5
一款自动刷新浏览器的小工具,它通过监听用户的按键,如果在键盘按下 Ctrl+S ,则自动刷新浏览器,操作十分简单,前端开发必备神器,快速提升工作效率,支持IE.火狐以及最新版的chrome33.之前我 ...
- Python 自动操作浏览器
1. 安装库 pip install selenium # Windows电脑安装selenium pip3 install selenium # Mac电脑安装selenium 2.安装浏览器驱动 ...
- java操作浏览器_java selenium 操作浏览器实例
导读热词 本篇文章介绍selenium 操作浏览器 阅读目录 浏览器最大化 前进,后退, 刷新 截图操作 模拟鼠标操作 杀掉Windows浏览器进程 浏览器最大化 前进,后退, 刷新 public s ...
- Android自动操作辅助工具思路分享
效果1: 效果2: 此次开发的工具都用纯原生代码进行Android的应用开发的,其实原理都是用了无障碍功能(AccessibilityService)进行处理.上个版本的工具太麻烦了,还需要进行相应的 ...
- 中山大学羽毛球场馆自动订场(Python+selenium+百度aip)
双鸭山南校人太多,小伙伴们日常约球抢不到室内的场馆,只好去室外打.所以趁考完试有时间写了一个自动抢羽毛球场的脚本,网好的时候20秒订场无压力.下面来分享一波这个脚本的一些技术细节(重点讲一下图像降噪和 ...
- selenium实现浏览器的自动操作
有的网站页面交互复杂,所使用的技术难以被爬取,比如,腾讯文档. 还有的网站,对URL的加密逻辑很复杂. 想要攻破这些网站的反爬虫技术会有一些难度. 不过selenium,通过它,可以解决以上所有问题. ...
- python使用selenium模块实现火车票的自动购买
python使用selenium模块实现火车票的自动购买 python使用selenium模块实现火车票的自动购买 实现功能描述 直接撸代码 总结 实现功能描述 程序运行后会打开一个浏览器界面定义其尺 ...
最新文章
- 学习ASP.NET MVC系列 - 还有比这更简炼的吗?把复杂的事情变简单了,贡献啊!...
- modelsim仿真正确FPGA运行不正确的可能原因 - cm4写寄存器错
- redis的scan命令的源码分析,实现原理
- vue中mixin 感觉很牛逼(父子组件融合成一个新组件)
- 面向对象设计原则之1-单一职责原则
- 实现.NET Core配置Provider之EF
- php投影,box-shadow实现不同角度的投影
- SQL Server 2005 如何自动备份数据库
- 【转】android新建项目时 出现appcompat_v7工程错误和红色感叹号
- DiscuzNT改造系列之删除帖子后论坛版块列表同步更新
- 父与子编程之旅第十章pygame下载+安装+pip更新
- 网页顶部广告展开与收起
- Virtual Table — RTTI — typeinfo dynamic_cast 模板编程 orocos OperationCaller 类的设计
- hp ux安装mysql5.1.56_详细讲解Linux环境下MySQL5.1安装步骤
- 【JavaWeb】之Tomcat介绍、安装与使用
- 一个程序员老总的年终总结2010版
- php虚拟主机搭建微信公众号服务器
- 计算机科学与技术脑电波,科学“读心术”,当脑电波扫描图遇到人工智能
- HTML中引入外部CSS和JS
- Python的作者吉多·范罗苏姆简介