03-selenium的使用

发布时间 2024-01-02 11:28:23作者: Way*yy

搜索文档数

find_all:找所有,返回列表
find:找一个 Tag对象


from bs4 import BeautifulSoup
import re

html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><b>The Dormouse's story</b><span>lqz</span></p>

<p class="story">Once upon a time there were three little sisters; and their names were
<a href="https://example.com/elsie" class="sister" id="link1">Elsie</a>,
<a href="https://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="https://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, "html.parser")
# 获取所有的P标签
res = soup.find_all("p")
# 获取标签名是P标签,类是title的P标签
res = soup.find(name="p", class_="title")
# 找出标签名字是span,文本内容是lqz的标签
res = soup.find(name="span", string="lqz")
# 找到属性href="https://example.com/tillie"的标签
res = soup.find(href="https://example.com/tillie")
# 属性可以写成这样
res = soup.find(attrs={"class": "story"})

# 正则  无论按标签名,按属性,按文本内容 都是按正则形式查找
# 找到所有名字以b开头的所有标签

obj = soup.find_all(name=re.compile('^b'))
obj = soup.find_all(name=re.compile('y$'))
obj = soup.find_all(href=re.compile('^http:'))
obj = soup.find_all(string=re.compile('i'))

# 列表  无论按标签名,按属性,按文本内容 都是按列表形式查找
# 找出所有p标签下的a标签
res = soup.find_all(name=["p", "a"])
# 找出所有类是sister和title的标签
res = soup.find_all(class_=["sister", "title"])

#  True无论按标签名,按属性,按文本内容 都是按布尔形式查找,返回列表形式
# 找出所有有id的标签
res = soup.find_all(id=True)
# 找出所有有href的标签
res = soup.find_all(href=True)
# 找出名字是a的并且有href属性的
res = soup.find_all(name='a', href=True)
print(res)


# 方法 无论按标签名,按属性,按文本内容 都是按方法形式查找
def has_class_but_no_id(tag):
    return tag.has_attr('class') and not tag.has_attr('id')

print(soup.find_all(name=has_class_but_no_id))

爬取照片

import requests
from bs4 import BeautifulSoup

response = requests.get(url="http://www.daimg.com/photo/people/")
response.encoding = "gbk"
soup = BeautifulSoup(response.text, "html.parser")
res_list = soup.find_all(name="img", title=True)
print(res_list)
for res in res_list:
    img_url = res["src"]
    print(img_url)
    img = requests.get(url=img_url)
    print(img)
    name = img_url.split('/')[-1]
    print(name)
    with open("./img/%s" % name, "wb") as f:
        for line in img.iter_content():
            f.write(line)
            print("结束")

bs4其它用法

#1、find_all 其他参数
    -limit=数字   找几条 ,如果写1 ,就是一条
    -recursive
    
#2、搜索文档树和遍历文档树可以混用,找属性,找文本跟之前学的一样

css选择器

# id选择器
	#id号
# 标签选择器
	#标签名
# 类选择器
	#.类名
    
# 记住的:
    #id、.sister、head
    div>a  # div下直接子节点a
    div a  # div下子子孙孙节点a
 

# 一旦会了css选择器的用法--->以后所有的解析库都可以使用css选择器去找
import requests
from bs4 import BeautifulSoup

res = requests.get('https://www.cnblogs.com/liuqingzheng/p/16005896.html')
# print(res.text)
soup = BeautifulSoup(res.text, 'html.parser')
# a=soup.find(name='a',title='下载哔哩哔哩视频')
# print(a.attrs.get('href'))

# p=soup.select('#cnblogs_post_body p:nth-child(2) a:nth-child(5)')[0].attrs.get('href')
# p=soup.select('#cnblogs_post_body > p:nth-child(2) > a:nth-child(5)')[0].attrs.get('href')  # 以后直接复制即可
p=soup.select('a[title="下载哔哩哔哩视频"]')[0].attrs.get('href')  # 以后直接复制即可
print(p)

selenium基本使用

主要功能:
    1、这个模块:既能发请求,又能解析,还能执行js
    2、selenium最初是一个自动化测试工具,而爬虫中使用它主要是为了解决requests无法直接执行JavaScript代码的问题

    3、selenium 会做web方向的自动化测试
    4、appnium 会做 app方向的自动化测试
   	5、selenium 可以操作浏览器,模拟人的 行为
    
如何使用:
    1 下载浏览器驱动:https://edgedl.me.gvt1.com/edgedl/chrome/chrome-for-testing/119.0.6045.105/win64/chromedriver-win64.zip,跟浏览器型号和版本一一对应的
    2 安装 selenium
    3 写python代码,操作浏览器
    
import time
from selenium import webdriver
# 跟人操作浏览器一样,打开了谷歌浏览器,拿到浏览器对象
bro=webdriver.Chrome()
# 在地址栏中输入地址
bro.get('https://www.baidu.com')
time.sleep(5)
bro.close()

模拟登录

import time

from selenium import webdriver
from selenium.webdriver.common.by import By

bro = webdriver.Chrome()
bro.get('https://www.baidu.com')
bro.implicitly_wait(10)  # 设置等待---》从页面中找标签,如果找不到,就等待
# 最大化
bro.maximize_window()
# print(bro.page_source) # 当前页面的html内容
# 找到登录按钮--》选择器---》css选择器
# a_login=bro.find_element(by=By.NAME,value='tj_login')
# a_login=bro.find_element(by=By.ID,value='s-top-loginbtn')
a_login = bro.find_element(by=By.LINK_TEXT, value='登录')  # a 标签连接文字
time.sleep(2)
# 点击
a_login.click()

# 找到短信登录 点击
sms_login = bro.find_element(by=By.ID, value='TANGRAM__PSP_11__changeSmsCodeItem')
sms_login.click()
time.sleep(1)
user_login = bro.find_element(by=By.ID, value='TANGRAM__PSP_11__changePwdCodeItem')
user_login.click()
time.sleep(1)
username = bro.find_element(by=By.NAME, value='userName')
# 往输入框中写文字
username.send_keys('lqz@qq.com')
password = bro.find_element(by=By.ID, value='TANGRAM__PSP_11__password')
# 往输入框中写文字
password.send_keys('lqz@qq.com')

agree = bro.find_element(By.ID, 'TANGRAM__PSP_11__isAgree')
agree.click()
time.sleep(1)

submit = bro.find_element(By.ID, 'TANGRAM__PSP_11__submit')
submit.click()

time.sleep(3)
bro.close()

selenium其它用法

无头浏览器

# 如果我们做爬虫,我们只是为了获取数据,不需要非有浏览器在显示--->隐藏浏览器图形化界面


import time

from selenium import webdriver
from selenium.webdriver.common.by import By


from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_argument('blink-settings=imagesEnabled=false') #不加载图片, 提升速度
chrome_options.add_argument('--headless') #浏览器不提供可视化页面. linux下如果系统不支持可视化不加这条会启动失败
bro = webdriver.Chrome(options=chrome_options)


bro.get('https://www.cnblogs.com/liuqingzheng/p/16005896.html')

print(bro.page_source)
time.sleep(3)
bro.close()

搜索标签

# 1 搜索标签
# By.ID  # 根据id号查找标签
# By.NAME  # 根据name属性查找标签
# By.TAG_NAME  # # 根据标签查找标签
# By.CLASS_NAME # 按类名找
# By.LINK_TEXT # a标签文字
# By.PARTIAL_LINK_TEXT # a标签文字,模糊匹配
#---------selenium 自己的--------
# By.CSS_SELECTOR # 按css选择器找
# By.XPATH  #按xpath找


# 2 获取标签的属性,文本,大小,位置
# print(tag.get_attribute('src'))
# print(tag.id)  # 这个id不是id号,不需要关注
# print(tag.location)
# print(tag.tag_name)
# print(tag.size)

import time
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.common.by import By


from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_argument('blink-settings=imagesEnabled=false') #不加载图片, 提升速度
chrome_options.add_argument('--headless') #浏览器不提供可视化页面. linux下如果系统不支持可视化不加这条会启动失败
bro = webdriver.Chrome(options=chrome_options)


bro.get('https://www.cnblogs.com/liuqingzheng/p/16005896.html')

#### 不建议使用----》selenium提供的查找
# soup=BeautifulSoup(bro.page_source,'html.parser')
# print(soup.find(title='下载哔哩哔哩视频').attrs.get('href'))


# selenium提供的查找
# By.ID  # 根据id号查找标签
# By.NAME  # 根据name属性查找标签
# By.TAG_NAME  # # 根据标签查找标签
# By.CLASS_NAME # 按类名找
# By.LINK_TEXT # a标签文字
# By.PARTIAL_LINK_TEXT # a标签文字,模糊匹配
#---------selenium 自己的--------
# By.CSS_SELECTOR # 按css选择器找
# By.XPATH  #按xpath找

#### 找到标签后,获取标签属性,文本,位置,大小等
# print(tag.get_attribute('src'))
# print(tag.id)  # 这个id不是id号,不需要关注
# print(tag.location)
# print(tag.tag_name)
# print(tag.size)
div=bro.find_element(By.ID,'cnblogs_post_body')
# res=div.get_attribute('class')   # 获取标签属性
print(div.get_attribute('class'))
print(div.id)  # 这个id不是id号,不需要关注
print(div.location) # 在页面中位置: x y轴效果---》
print(div.tag_name) # 标签名
print(div.size) # 标签大小  x y
print(div.text) # 文本内容


## 找到页面中所有div
# divs=bro.find_elements(By.TAG_NAME,'div')
# print(len(divs))

# 按类名找
# div=bro.find_element(By.CLASS_NAME,'postDesc').text
# print(div)


# 按css选择器
# div=bro.find_element(By.CSS_SELECTOR,'div.postDesc').text
# div=bro.find_element(By.CSS_SELECTOR,'#topics > div > div.postDesc').text
# print(div)

# 按xpath选择---专门学xpath的语法
# div=bro.find_element(By.XPATH,'//*[@id="topics"]/div/div[3]').text
# print(div)


time.sleep(1)
bro.close()