尚硅谷爬虫note011
一、selenium
# _*_ coding : utf-8 _*_
# @Time : 2025/2/20 15:41
# @Author : 20250206-里奥
# @File : demo15_selenium_元素信息及交互
# @Project : PythonPro17-21
from selenium import webdriver
from demo14_selenium_元素定位 import browser
path = 'chromedriver.exe'
browser = webdriver.Chrome(path)
url = 'https://www.baidu.com'
browser.get(url)
input = browser.find_element_by_id('su')
# 获取标签属性
print(input.get_attribute('class'))
# 获取标签名字
print(input.tag_name)
#获取元素文本
a = browser.find_element_by_link_text('新闻')
print(a.text)
# _*_ coding : utf-8 _*_
# @Time : 2025/2/21 09:46
# @Author : 20250206-里奥
# @File : demo16_selenium_交互
# @Project : PythonPro17-21
# 导入selenium
from selenium import webdriver
from demo14_selenium_元素定位 import browser
#创建浏览器对象
path = 'chromedriver.exe'
browser = webdriver.Chrome(path)
# url
url = 'http://www.baidu.com'
browser.get(url)
#睡眠2秒
import time
time.sleep(2)
#获取文本框对象
input = browser.find_element_by_id('kw')
# 在文本框中输入景甜
input.send_kyes('景甜')
time.sleep(2)
#获取百度一下的按钮
button = browser.find_element_by_id('su')
#点击按钮
button.click()
time.sleep(2)
#滑到底部
js_buttom = 'document.documentElement.scrollTop = 100000'
#执行js_buttom
browser.execute_script(js_buttom)
time.sleep(2)
# 获取下一页的链接
next = browser.find_element_by_xpath('//a[@class = "n"]')
# 点击下一页
next.click()
time.sleep(2)
# 回到上一页
browser.back()
time.sleep(2)
#回去
browser.forward()
time.sleep(3)
#退出
browser.quit()
二、提升selenium运行效率(2个)
1. phantomjs
无界面浏览器
支持页面元素查找,js的执行等
不进行css和gui的渲染,运行效率比真实浏览器快
1)使用
1. 下载phantomjs
2. 拷贝phantomjs.exe文件到项目工程中
# _*_ coding : utf-8 _*_
# @Time : 2025/2/21 10:51
# @Author : 20250206-里奥
# @File : demo17_selenium_phantomjs的基本使用
# @Project : PythonPro17-21
from selenium import webdriver
from demo14_selenium_元素定位 import browser
path = 'phantomjs.exe'
browser = webdriver.PhantomJS(path)
url = 'https://www.baidu.com'
browser.get(url)
#快照
browser.save_screenshot('baidu.png')
import time
time.sleep(2)
input = browser.find_element_by_id('kw')
input.send_keys('景甜')
time.sleep(2)
browser.save_screenshot('景甜.png')
2.chrome handless
不打开ui界面,可以使用chrome浏览器,运行效果和chrome保持一致
系统需求:
Windows系统——》版本>=60
python版本——》版本>3.6
selenium版本——》版本>3.4
chromedriver版本——》版本>2.3