首页 > 其他分享 >爬虫之bs4搜索文档树和selenium

爬虫之bs4搜索文档树和selenium

时间:2022-11-25 16:14:44浏览次数:36  
标签:bs4 标签 selenium 爬虫 bro res import find


一、bs4搜索文档叔

# 搜索文档树有五种搜索方式:
     字符串、正则表达式、列表、True、方法
# find  查找一个    find_all  查找所有

from bs4 import BeautifulSoup

html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p id="my p" class="title">asdfasdf<b id="bbb" class="boldest">The Dormouse's story</b>
</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')

1.1 字符串搜索

# 1.1 字符串:可以按照标签名,属性名查找
res=soup.find(name='a',id='link2')# 查找a标签id为link2的标签 其实我们可以直接写id 因为id是唯一的
res=soup.find(href='http://example.com/tillie')  # 查找href等于后面参数的标签
res=soup.find(class_='story')  # 查找class等于 story的标签
res=soup.body.find('p')  # 查找body下的p标签
res=soup.body.find(string='Elsie')  # 查找body下的文本信息为Elsie的标签
res=soup.find(attrs={'class':'sister'})  # 查找class等于sister的标签
print(res) 

1.2 正则表达式搜索

# 1.2 正则表达式  标签名,属性可以使用正则匹配
import re
res=soup.find_all(name=re.compile('^b'))  # 查找所有以b开头的标签
res=soup.find_all(href=re.compile('^http'))  # 查找所有以http开头的标签
for item in res:  # 因为查找到的是a标签 我们想要a标签中的地址的话 我们需要在过滤一遍
    url=item.attrs.get('href')
    print(url)  # 这就获取到了页面中的所有的链接地址

res=soup.find(attrs={'href':re.compile('^a')})
print(res)

1.3 列表搜索

# 1.3 列表  标签名,属性名  等于列表  或条件
res=soup.find_all(class_=['story','sister'])  # 或条件  把属性为story或则sister查找出来
res=soup.find_all(name=['a','p'])  # 或条件 把标签a和p查找出来
print(res)

1.4 True搜索

# 5.4 True  标签名,属性名  等于布尔
res = soup.find_all(name=True)  # 有标签名的所有标签  没有标签就不会查找出来
print(res)

# 拿出页面中所有图片
res = soup.find_all(src=True)  # 因为有src属性才会True 才会被查找所以res就只有src属性的标签
for item in res:
    url = item.attrs.get('href')  # 然后在把该标签中的href查找出来即可
    print(url)

1.5 方法

# 其实就是写一个函数

# 5.5 方法  标签名或属性名 = 方法
def has_class_but_no_id(tag):
    return tag.has_attr('class') and not tag.has_attr('id')  
    # 返回了标签中有class和不能有id的

print(soup.find_all(has_class_but_no_id))  #  然后查找所有

1.6 其他方法

## 其他 find_all的其他属性   limit    recursive:False,只找一层
res=soup.find_all(name='a',limit=2)   # 找两个a标签
# find的本质是find_all + limit=1

res=soup.body.find(name='p',id=False).find_all(name='a',recursive=False)  
# 只在当前层中找一个 没有就返回None 所以需要一层一层的写   这样会找的快效率高

print(res)


## 修改文档树:bbs,删除script标签

'''
总结:
    1  find和find_all  查找一个和查找全部
    2  5 种搜索方法
    3  结合遍历文档树一起使用,提交查询速度
'''

二、css选择器

# bs4 可以通过遍历,搜索,css选择器选择标签

# 还是按照上面的文本查找

soup = BeautifulSoup(html_doc, 'lxml')
res=soup.select('a')  # 查找a标签
res=soup.select('#link1')  # 查找id为link1的标签
res=soup.select('.sister')  # 查找类属性为sister的标签
res=soup.select('body>p>a')  # 查找body下的p下的a标签
# 只需要会了css选择,几乎所有的解析器[bs4,lxml...],都会支持css和xpath


res=soup.select('body>p>a:nth-child(2)')  # 查找body下的p下的a标签  取两个
res=soup.select('body>p>a:nth-last-child(1)')  # 这是取最后一个

# [attribute=value]
res=soup.select('a[href="http://example.com/tillie"]')  # a标签中 href属性等于后面的参数 查找
print(res)


'''
记住的:
    1  标签名
    2  .类名
    3  #id号
    4 body a   body下子子孙孙中得a
    5 body>a  body下子的a,没有孙
    6 其他的参照css选择器
'''

三、selenium基本使用

# requests 发送http请求获取数据,获取数据是xml使用bs4解析,解析出咱么想要的数据
    -使用requests获取回来的数据,跟直接在浏览器中看到的数据,可能不一样
    -requests不能执行js
    -如果使用requets,需要分析当次请求发出了多少请求,每个都要发送一次,才能拼凑出网页完整的数据
    -所以需要借助其他模块来完成 执行js代码


# selenium 操作浏览器,控制浏览器,模拟人的行为
# 人为点:功能测试
# 自动化测试(接口测试,压力测试),网站,认为点,脚本    appnium
# 测试开发 
selenium最初是一个自动化测试工具,而爬虫中使用它主要是为了解决requests无法直接执行JavaScript代码的问题
selenium本质是通过驱动浏览器,完全模拟浏览器的操作,比如跳转、输入、点击、下拉等,来拿到网页渲染之后的结果,可支持多种浏览器

3.1 使用

    -安装模块:pip3 install selenium
    -下载浏览器驱动:selenium操作浏览器,需要有浏览器(谷歌浏览器),谷歌浏览器驱动
        -https://registry.npmmirror.com/binary.html?path=chromedriver/
        -浏览器版本对应的驱动
        106.0.5249.119    找到相应的驱动
        
    -写代码测试
    from selenium import webdriver
    import time

    # 驱动放到环境变量中,就不用传这个参数了
    # 打开一个浏览器
    bro = webdriver.Chrome(executable_path='./chromedriver.exe')  # 这个官网已经要弃用了 但是还是能够使用  我们只需要把参数放到环境变量中即可
    # 在地址栏输入 网站
    bro.get('http://www.baidu.com')  # 想这个网站发送get请求

    time.sleep(3)
    bro.close()  # 关闭tab页 就是一个一个页面
    bro.quit()  # 关闭浏览器

四、无界面浏览器

# 做爬虫的 其实是不希望一个浏览器打开的,谷歌是支持无头浏览器的,就是后台运行,没有浏览器的图形化(GUI)界面

4.1 代码演示

from selenium import webdriver
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下如果系统不支持可视化不加这条会启动失败
chrome_options.binary_location = r"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"  # 手动指定使用的浏览器位置  不加也没事  就是你的浏览器的位置在哪

bro = webdriver.Chrome(executable_path='./chromedriver.exe', options=chrome_options)  # 只要把参数加上 就不会有浏览器界面了 浏览器只会在后台运行

# 在地址栏输入 网站
bro.get('https://www.jd.com/')  # 向这个网站发送get请求 返回内容
print(bro.page_source) # 浏览器中看到的页面的内容

time.sleep(3)
bro.close()  # 关闭tab页
bro.quit()  # 关闭浏览器

五、selenium其他用法

5.0 小案例 自动登入百度

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

bro = webdriver.Chrome(executable_path='./chromedriver.exe')

bro.get('http://www.baidu.com')
bro.implicitly_wait(10) # 等待,如果十秒内没有加载出来,就会报错,十秒内加载出来就不会报错
bro.maximize_window() # 全屏
# 通过 a标签文字内容查找标签的方式
a = bro.find_element(by=By.LINK_TEXT, value='登录')  # 打开页面之后 找到登入按钮
# 点击标签
a.click()  # 相当于鼠标点击了登入按钮

# 页面中id唯一,如果有id,优先用id  然后在找到输入用户名的地方
input_name = bro.find_element(by=By.ID, value='TANGRAM__PSP_11__userName')  
# 输入用户名
input_name.send_keys('[email protected]')  # 然后在自动输入用户名

time.sleep(1)  # 等待1秒

# 在通过id找到输入密码的输入框
input_password = bro.find_element(by=By.ID, value='TANGRAM__PSP_11__password')
input_password.send_keys('lqz12345')  # 自动输入密码
time.sleep(1)  # 等待1秒

# 在找到登入按钮 通过id找到
input_submit = bro.find_element(by=By.ID, value='TANGRAM__PSP_11__submit')
# 点击
input_submit.click()  # 相当于鼠标点击按钮
time.sleep(5)  # 等待5秒

bro.close()  # 然后就关闭页面

5.1 获取位置属性大小,文本

'selenium 的用法'
# 查找标签
bro.find_element(by=By.ID,value='id号')  # 根据id查找标签
bro.find_element(by=By.LINK_TEXT,value='a标签文本内容')  # 通过标签的文本内容查找
bro.find_element(by=By.PARTIAL_LINK_TEXT,value='a标签文本内容模糊匹配')  # 还可以模糊匹配
bro.find_element(by=By.CLASS_NAME,value='类名')  # 根据标签的类名查找
bro.find_element(by=By.TAG_NAME,value='标签名')  # 根据标签名查找
bro.find_element(by=By.NAME,value='属性name')  # 根据属性名查找
# -----通用的----
bro.find_element(by=By.CSS_SELECTOR,value='css选择器')  # 根据css选择器查找
bro.find_element(by=By.XPATH,value='xpath选择器')


# 获取标签位置,大小
print(code.location)  # 获取标签在页面上的位置  是x,y轴显示
print(code.size)  # 获取标签的大小
-------
print(code.tag_name)  # 获取标签的标签名
print(code.id)  # 获取标签的id

5.1.1 代码演示

# 我们可以把12306的扫码登入的二维码存到本地
from selenium import webdriver
from selenium.webdriver.common.by import By
import time
import base64

bro = webdriver.Chrome(executable_path='./chromedriver.exe')
bro.get('https://kyfw.12306.cn/otn/resources/login.html')  # 向12306发送get请求
bro.implicitly_wait(10)
bro.maximize_window()  # 全屏

a = bro.find_element(by=By.LINK_TEXT, value='扫码登录')  # 根据文本内容找到扫码登入

a.click()  # 然后点击跳到扫码登入页面

code = bro.find_element(by=By.CSS_SELECTOR, value='#J-qrImg')  # 然后在通过id获取这个二维码

# 方案一:通过位置,和大小,截图截出来
print(code.id)  # 这样我们就可以获取这个二维码的所有信息了 这是官网给二维码生成的id
print(code.location)  # 二维码在页面上的位置
print(code.tag_name)  # 二维码的标签姓名
print(code.size)  # 二维码的大小
# 方案二:通过src属性获取到图片
s = code.get_attribute('src')  # 通过查找属性src的获取二维码的链接地址
print(s)
with open('code.png','wb') as f:
    res=base64.b64decode(s.split(',')[-1])  # 因为真正的地址是,后面的 所以需要分割
    f.write(res)

time.sleep(3)

bro.close()

5.2 等待元素加载

# 代码执行很快,有些标签还没加载出来,直接取,取不到
# 等待
    -显示等待:一般不用,需要指定等待哪个标签,如果标签很多,每个都要设置比较麻烦
    -隐士等待:
        bro.implicitly_wait(10)
        find找标签的时候,如果找不到,等最多10s钟

5.3 元素操作

# 点击
标签.click()
# input写文字
标签.send_keys('文字')  # 输入框中输入信息
# input清空文字
标签.clear()

# 模拟键盘操作
from selenium.webdriver.common.keys import Keys
input_search.send_keys(Keys.ENTER)  # 模拟 按下回车键

5.4 执行js代码

import time

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

bro = webdriver.Chrome(executable_path='./chromedriver.exe')
bro.get('https://www.jd.com/')

# 1 能干很多事情,打印了cookie
bro.execute_script('alert(document.cookie)')  # 弹出该页面的cookie

# 2 滚动页面,到最底部
# 一点点向下滑动
for i in range(10):  # 400的长度循环十次 就是一点点的向下滑动了
    y=400*(i+1)
    bro.execute_script('scrollTo(0,%s)'%y)
    time.sleep(1)
# 一次性直接滑动到最底部
bro.execute_script('scrollTo(0,document.body.scrollHeight)') 
# 这是首先获取body的长度 其实就是滑到最底部了

time.sleep(3)
bro.close()

5.5 切换选项卡

import time

from selenium import webdriver

bro = webdriver.Chrome(executable_path='./chromedriver.exe')
bro.get('https://www.jd.com/')  # 向京东发送get请求

# 使用js打开新的选项卡
bro.execute_script('window.open()')  # 其实就是打开一个页面 只不过是空的

time.sleep(2)

# 切换到这个选项卡上,刚刚打开的是第一个
bro.switch_to.window(bro.window_handles[1])  # 然后切换到刚刚打开的页面 就是空的页面
time.sleep(2)
bro.get('http://www.taobao.com')  # 然后向淘宝发送get请求
time.sleep(2)
bro.switch_to.window(bro.window_handles[0])  # 然后在返回到京东页面

time.sleep(3)
bro.close()
bro.quit()

5.6 浏览器的前进和后退

import time

from selenium import webdriver

bro = webdriver.Chrome(executable_path='./chromedriver.exe')
bro.get('https://www.jd.com/')  #  打开京东页面  都是单页面打开

time.sleep(2)
bro.get('https://www.taobao.com/')  # 打开淘宝页面

time.sleep(2)
bro.get('https://www.baidu.com/')  # 打开百度页面

# 后退一下
bro.back()  # 后退其实就是 从百度页面退到了淘宝页面
time.sleep(1)
# 前进一下
bro.forward()  # 前进就是 又从淘宝页面前进到了百度页面
time.sleep(3)
bro.close()

5.7 异常处理

from selenium.common.exceptions import TimeoutException,NoSuchElementException,NoSuchFrameException
try:

except Exception as e:  # 有很多报错
    print(e)
finally:
    bro.close()

# 这是表中模板 不管获取的页面有没有报错 都要关闭

六、selenium登入cnblogs获取cookie

# 操作浏览器,登录成功就可以拿到登录成功的cookie,保存到本地
# 如果有很多小号,会有很多cookie,搭建cookie池

# 然后我们就可以拿着这个cookie向cnblogs发送请求  会认为我们发送的请求是登入的

6.1 代码演示

import time

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
import json


# 登录过程  获取cookie
bro = webdriver.Chrome(executable_path='./chromedriver.exe')
bro.get('https://www.cnblogs.com/')
bro.implicitly_wait(10)
try:
   # 找到登录按钮
    submit_btn = bro.find_element(By.LINK_TEXT, value='登录')
    submit_btn.click()
    time.sleep(1)
    username = bro.find_element(By.ID, value='mat-input-0')
    password = bro.find_element(By.ID, value='mat-input-1')
    username.send_keys("[email protected]")
    password.send_keys('sadfasdfads')

    submit = bro.find_element(By.CSS_SELECTOR,
                              value='body > app-root > app-sign-in-layout > div > div > app-sign-in > app-content-container > div > div > div > form > div > button')

    time.sleep(20)
    submit.click()
   # 会有验证码,滑动,手动操作完了,敲回车,程序继续往下走  如果有验证码手动完成即可
    input()  # 然后在敲回车即可
    # 已经登录成功了

    cookie = bro.get_cookies()  # 然后获取cookie
    print(cookie)
    with open('cnblogs.json', 'w', encoding='utf-8') as f:
         json.dump(cookie, f)  # 存到本地

    time.sleep(5)
except Exception as e:
   print(e)
finally:
   bro.close()

6.2 利用cookie访问cnblog

#  打开cnblose,自动写入cookie,我就是登录状态了
bro = webdriver.Chrome(executable_path='./chromedriver.exe')
bro.get('https://www.cnblogs.com/')
bro.implicitly_wait(10)
time.sleep(3)
# 把本地的cookie写入,就登录了
with open('cnblogs.json','r',encoding='utf-8') as f:
    cookie=json.load(f)

for item in cookie:
    bro.add_cookie(item)  # 将本地的cookie写入到cnblog中


# 刷新一下页面
bro.refresh()
time.sleep(10)
bro.close()

七、抽屉半自动点赞

# 使用selenium登录到抽屉,获取到,使用requests,自动点赞
    -使用requests登录,非常难登录,因为有验证码
from selenium import webdriver
from selenium.webdriver.common.by import By
import time
import json
import requests

bro = webdriver.Chrome(executable_path='./chromedriver.exe')

bro.get('https://dig.chouti.com/')
bro.implicitly_wait(10)
try:
    # 自动登入
    submit = bro.find_element(by=By.ID, value='login_btn')  # 找到登入按钮
    bro.execute_script("arguments[0].click()", submit)  # 点击登入按钮
    # submit.click() # 有的页面button能找到,但是点击不了,报错,可以使用js点击它
    time.sleep(2)
    username = bro.find_element(by=By.NAME, value='phone')  # 找到用户名
    username.send_keys('18953675221')  # 输入手机号
    password = bro.find_element(by=By.NAME, value='password')  # 找到密码
    password.send_keys('lqz123')  # 输入密码
    time.sleep(3)
    submit_button = bro.find_element(By.CSS_SELECTOR,
                                     'body > div.login-dialog.dialog.animated2.scaleIn > div > div.login-footer > div:nth-child(4) > button')  # 找到登入按钮
    submit_button.click()  # 点击登入

    # 如果有验证码 手动输入即可
    input()
    cookie = bro.get_cookies()  # 获取cookie
    print(cookie)
    with open('chouti.json', 'w', encoding='utf-8') as f:
        json.dump(cookie, f)  # 存到本地

    # 找出所有文章的id号  通过类属性找到所有的文章
    div_list = bro.find_elements(By.CLASS_NAME, 'link-item')
    l = []
    for div in div_list:
        article_id = div.get_attribute('data-id')  # 通过data-id属性找到所有文章的id
        l.append(article_id)



except Exception as e:
    print(e)

finally:
    bro.close()

#  继续往下写,selenium完成它的任务了,登录---》拿到cookie,使用requests发送[点赞]

print(l)

with open('chouti.json', 'r', encoding='utf-8')as f:  # 将cookie提取出来
    cookie = json.load(f)  # 所以cookie是一个对象 所以需要处理
# 小细节,selenium的cookie不能直接给request用,需要有些处理
request_cookies = {}
for item in cookie:
    request_cookies[item['name']] = item['value']
print(request_cookies)
header = {  # 请求头
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36'
}
for i in l:  # 将所有的文章id循环出来
    data = {
        'linkId': i
    }
    res = requests.post('https://dig.chouti.com/link/vote', data=data, headers=header, cookies=request_cookies)  # 像文章id发送请求 相当于点赞
    print(res.text)

 

标签:bs4,标签,selenium,爬虫,bro,res,import,find
From: https://www.cnblogs.com/stephenwzh/p/16925467.html

相关文章