selenuim

编辑本随笔

selenum打开浏览器进行操作:

创建浏览器对象

#浏览器对象通过以下方法定位到指定元素,定位之后即可对其操作
#find_element_by_id            根据id找节点
#find_elements_by_name         根据name找
#find_elements_by_xpath        根据xpath查找
#find_elements_by_tag_name     根据标签名找
#find_elements_by_class_name   根据class名字查找

项目一、百度搜索指定词条

#需求:让百度进行一个词条搜索操作

from selenium import webdriver

#创建一个浏览器对象
bro=webdriver.Chrome(executable_path="./chromedriver.exe")

#get方法指定一个url,让浏览器进行请求
bro.get("https://www.baidu.com")

#定位到text文本框
text=bro.find_element_by_id("kw")
#填写搜索关键字
text.send_keys("人民币")

#定位搜索按钮
button=bro.find_element_by_id("su")
#点击搜索按钮
button.click()

#关闭浏览器
bro.quit()
View Code

phantomJs:无界面浏览器操作

驱动下载地址

使用流程和使用浏览器方式一样

项目二、使用PhantomJs模拟浏览器使用百度搜索

from selenium import webdriver
import time
#创建PhantomJs对象
pjs=webdriver.PhantomJS(executable_path="./phantomjs.exe")

#用get方式打开www.baidu.com
pjs.get("https://www.baidu.com")

#截图保存
pjs.save_screenshot('./1.png')

#定位到搜索框
text=pjs.find_element_by_id('kw')

#输入搜索关键字
text.send_keys("人民币")

#截图保存
pjs.save_screenshot('./2.png')

#定位到搜索按钮
btn=pjs.find_element_by_id("su")

#点击搜索
btn.click()

time.sleep(3)

#截图保存
pjs.save_screenshot('./3.png')

#关闭
pjs.close()

提示使用无头版的chrome或Firefox

 项目三、使用PhantomJs执行js代码,使浏览器滚动到最底部

from selenium import webdriver
import time

#定义PhantomJs浏览器对象
bro=webdriver.PhantomJS(executable_path="./phantomjs.exe")

#定义url
url="https://movie.douban.com/tag/#/?sort=U&range=0,10&tags=%E7%BB%BC%E8%89%BA"

#对url发起请求
bro.get(url)

time.sleep(3)

bro.save_screenshot("./1.png")

#编写js代码,可以在浏览器的调试工具里面去调试。使浏览器滚动到最下方
js="window.scrollTo(0,document.body.scrollHeight)"

#执行js代码,让浏览器滚动到底部,加载更多的数据
bro.execute_script(js)

#获取加载数据后的页面。page_source
time.sleep(3)

bro.save_screenshot("./2.png")

page_text=bro.page_source
原文地址:https://www.cnblogs.com/yaya625202/p/10397221.html