bs4遍历文档树,搜素文档树,find_all参数,selenium,模拟登陆百度

2023-05-16

这里写目录标题

  • 一.昨日回顾
  • 二.今日内容
    • 1.bs4遍历文档树
    • 2.bs4的搜索文档树
    • 3.find_all的其他参数
    • 4.css选择器
    • 5.selenium的介绍
    • 6.selenium的使用
    • 7.模拟登陆百度
    • 8.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)


3.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/
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 webdriver

import time

bro=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 webdriver

bro=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()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

bs4遍历文档树,搜素文档树,find_all参数,selenium,模拟登陆百度 的相关文章

随机推荐

  • AMI主板BIOS菜单图文讲解设置!

    电脑硬件 xff0c 包括电脑中所有物理的零件 xff0c 以此来区分它所包括或执行的数据和为硬件提供指令以完成任务的软件 主要包含 机箱 xff0c 主板 xff0c 总线 xff0c 电源 xff0c 硬盘 xff0c 存储控制器 xf
  • luffy-02

    这里写目录标题 一 昨日回顾二 今日内容1 路飞前台配置 1 重构项目目录 2 文件修订 xff1a 目录中非配置文件的多余文件可以移除router的使用 3 前台配置 全局样式 配置文件 axios vue cookies element
  • luffy-03

    这里写目录标题 一 昨日回顾二 今日内容1 跨域问题1 1后端自己处理跨域简单请求非简单请求中间件处理 1 2前端处理跨域App vuevue config js 2 头部组件 尾部组件components Header vuecompon
  • luffy-04

    这里写目录标题 一 昨日回顾二 今日内容1 路飞项目使用xadmin2 首页轮播图接口 轮播图表 视图类 轮播图数量4 通过配置实现 前端对接 后续 接口缓存 3 git的使用3 1git的工作流程 4 git分支git提交代码出现冲突的2
  • luffy-05

    这里写目录标题 一 首页轮播图接口二 今日内容1 过滤文件2 从远端拉项目3 远程仓库3 1链接远程仓库的两种情况 4 冲突出现的原因及解决 一 首页轮播图接口 span class token number 1 span 首页轮播图接口
  • 手把手教你搭建鸿蒙hi3518开发和运行环境

    前言 学习 C 语言 xff0c C 43 43 语言 xff0c 数据结构和算法 xff0c 操作系统 xff0c 网络 xff0c 驱动 xff0c 设计模式等知识 用鸿蒙来强化就太对了 本文教你一步一步搭建鸿蒙的开发和运行环境 xff
  • luffy-06

    这里写目录标题 一 上节回顾二 今日内容1 ssh链接和https链接2 gitlab3 git远程分支合并4 git冲突出现原因及解决5 首页登录注册vue页面Header vueLogin vue 6 登录注册功能接口分析 一 上节回顾
  • luffy-07

    这里写目录标题 一 昨日回顾二 今日内容1 登录注册前端页面1 1Login vue1 2Register vue1 3Header vue 2 多方式登录接口3 手机号是否存在接口3 1路由层user urls py3 2user ser
  • luffy-08

    这里写目录标题 一 集成了腾讯短信 封装 luffyapi lib t sms settings pyluffyapi lib t sms sms py 二 短信验证码接口2 1路由 配置2 2视图 三 短信登录接口3 1视图3 2序列化类
  • luffy-09/redis

    这里写目录标题 一 昨日回顾二 今日内容1 redis介绍2 redis的Windows安装和配置3 普通链接和连接池3 1代码3 2redis pool py 4 redis之string操作5 redis之hash操作 一 昨日回顾 s
  • luffy-10/redis/celery简单介绍

    这里写目录标题 一 昨日回顾二 今日内容2 1redis之列表操作2 2 redis之其他操作2 3 redis之管道2 4 django中使用redis2 4 1通用方案redis pool pyviews py 2 4 2django提
  • luffy-11/celery

    这里写目录标题 一 昨日回顾二 今日内容1 celery基本使用2 celery多任务结构多任务结构小案例 3 高级使用之延时任务4 高级使用之定时任务5 django中使用celery6 首页轮播图定时更新6 1首页轮播图走redis缓存
  • luffy-12/课程页面前端,课程表数据录入,课程表分析,编写

    这里写目录标题 一 昨日回顾二 今日内容2 1课程页面前端2 2课程表分析 编写修改之前的一些数据 2 3课程表数据录入2 4课程分类接口 一 昨日回顾 span class token number 1 span celery span
  • luffy-13/课程接口,课程详情前台

    这里写目录标题 一 课程接口1 1 course serializer py1 2 course models py1 3course pagenation py1 4course SearchByName py1 5course view
  • luffy-14/课程详情,课程章节接口,课程详情前台,七牛云对象存储托管视频

    这里写目录标题 一 课程详情接口 课程章节接口1 1课程详情接口1 2课程章节接口1 3序列化类1 4路由 二 课程详情前台三 七牛云对象存储托管视频四 区间过滤 一 课程详情接口 课程章节接口 span class token numbe
  • luffy-15/区间过滤,搜索功能前端后端,支付宝

    这里写目录标题 一 区间过滤二 搜索功能2 1后端代码2 2前端搜索页面2 2 1views SearchCourse vue2 2 2router index js2 2 3components Header vue 三 支付宝3 0结构
  • QT工程:error: undefined reference to `QSerialPort::QSerialPort(

    问题 xff1a qt中使用QSerialPort时报错 error undefined reference to 96 QSerialPort QSerialPort 解决办法 xff1a 工程文件 pro里增加 xff1a QT 43
  • luffy-16/订单表设计,立即付款接口/前端,支付成功get回调用户展示,支付成功post回调修改订单状态

    这里写目录标题 一 昨日回顾二 今日内容1 订单表设计2 立即付款接口 一堆校验 登录后 2 1视图类2 2序列化类2 3自定义异常类2 4配置文件2 5路由 3 立即付款前端4 支付成功get回调用户展示4 1luffycity src
  • luffy-17/上线

    这里写目录标题 一 上节回顾二 今日内容1 购买阿里云服务器2 服务器配置 软件安装2 1更新系统软件包2 2安装mysql2 3安装redis2 4安装python3 62 5配置pip源 xff1a 阿里云不用配置 xff0c 默认配置
  • bs4遍历文档树,搜素文档树,find_all参数,selenium,模拟登陆百度

    这里写目录标题 一 昨日回顾二 今日内容1 bs4遍历文档树2 bs4的搜索文档树3 find all的其他参数4 css选择器5 selenium的介绍6 selenium的使用7 模拟登陆百度8 selenium的其他使用 一 昨日回顾