行业知识
selenium的使用
2026-10-20 02:35:48
来源:互联网转载
一 介绍
selenium最初是一个自动化测试工具,而爬虫中使用它主要是为了解决requests无法直接执行JavaScript代码的问题selenium本质是通过驱动浏览器,完全模拟浏览器的操作,比如跳转、输入、点击、下拉等,来拿到网页渲染之后的结果,可支持多种浏览器from selenium import webdriverbrowser=webdriver.Chrome()browser=webdriver.Firefox()browser=webdriver.PhantomJS()browser=webdriver.Safari()browser=webdriver.Edge()
官���:http://selenium-python.readthedocs.io
二 安装
1、有界面浏览器
#安装:selenium+chromedriverpip3 install selenium下载chromdriver.exe放到python安装路径的scripts目录中即可,注意最新版本是2.38,并非2.9国内镜像网站地址:http://npm.taobao.org/mirrors/chromedriver/2.38/最新的版本去官网找:https://sites.google.com/a/chromium.org/chromedriver/downloads#验证安装C:\Users\Administrator>python3Python 3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 18:41:36) [MSC v.1900 64 bit (AMD64)] on win32Type "help", "copyright", "credits" or "license" for more information.>>> from selenium import webdriver>>> driver=webdriver.Chrome() #弹出浏览器>>> driver.get('https://www.baidu.com')>>> driver.page_source#注意:selenium3默认支持的webdriver是Firfox,而Firefox需要安装geckodriver下载链接:https://github.com/mozilla/geckodriver/releases 2、无界面浏览器
PhantomJS不再更新
#安装:selenium+phantomjspip3 install selenium下载phantomjs,解压后把phantomjs.exe所在的bin目录放到环境变量下载链接:http://phantomjs.org/download.html#验证安装C:\Users\Administrator>phantomjsphantomjs> console.log('lqz gaga')lqz gagaundefinedphantomjs> ^CC:\Users\Administrator>python3Python 3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 18:41:36) [MSC v.1900 64 bit (AMD64)] on win32Type "help", "copyright", "credits" or "license" for more information.>>> from selenium import webdriver>>> driver=webdriver.PhantomJS() #无界面浏览器>>> driver.get('https://www.baidu.com')>>> driver.page_source 在 PhantomJS 年久失修, 后继无人的节骨眼
Chrome 出来救场, 再次成为了反爬虫 Team 的噩梦
自Google 发布 chrome 59 / 60 正式版 开始便支持Headless mode
这意味着在无 GUI 环境下, PhantomJS 不再是唯一选择 **
**
from selenium import webdriverfrom selenium.webdriver.chrome.options import Optionschrome_options = Options()chrome_options.add_argument('window-size=1920x3000') #指定浏览器分辨率chrome_options.add_argument('--disable-gpu') #谷歌文档提到需要加上这个属性来规避bugchrome_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" #手动指定使用的浏览器位置driver=webdriver.Chrome(chrome_options=chrome_options)driver.get('https://www.baidu.com')print('hao123' in driver.page_source)driver.close() #切记关闭浏览器,回收资源 三 基本使用
from selenium import webdriverfrom selenium.webdriver import ActionChainsfrom selenium.webdriver.common.by import By #按照什么方式查找,By.ID,By.CSS_SELECTORfrom selenium.webdriver.common.keys import Keys #键盘按键操作from selenium.webdriver.support import expected_conditions as ECfrom selenium.webdriver.support.wait import WebDriverWait #等待页面加载某些元素browser=webdriver.Chrome()try: browser.get('https://www.baidu.com')```input_tag=browser.find_element_by_id('kw')input_tag.send_keys('美女') #python2中输入中文错误,字符串前加个uinput_tag.send_keys(Keys.ENTER) #输入回车``` wait=WebDriverWait(browser,10) wait.until(EC.presence_of_element_located((By.ID,'content_left'))) #等到id为content_left的元素加载完毕,最多等10秒```print(browser.page_source)print(browser.current_url)print(browser.get_cookies())```finally: browser.close() 四 选择器
一 基本用法
#官网链接:http://selenium-python.readthedocs.io/locating-elements.htmlfrom selenium import webdriverfrom selenium.webdriver import ActionChainsfrom selenium.webdriver.common.by import By #按照什么方式查找,By.ID,By.CSS_SELECTORfrom selenium.webdriver.common.keys import Keys #键盘按键操作from selenium.webdriver.support import expected_conditions as ECfrom selenium.webdriver.support.wait import WebDriverWait #等待页面加载某些元素import timedriver=webdriver.Chrome()driver.get('https://www.baidu.com')wait=WebDriverWait(driver,10)try: #===============所有方法=================== # 1、find_element_by_id # 2、find_element_by_link_text # 3、find_element_by_partial_link_text # 4、find_element_by_tag_name # 5、find_element_by_class_name # 6、find_element_by_name # 7、find_element_by_css_selector # 8、find_element_by_xpath # 强调: # 1、上述均可以改写成find_element(By.ID,'kw')的形式 # 2、find_elements_by_xxx的形式是查找到多个元素,结果为列表```#===============示范用法===================# 1、find_element_by_idprint(driver.find_element_by_id('kw'))# 2、find_element_by_link_text# login=driver.find_element_by_link_text('登录')# login.click()# 3、find_element_by_partial_link_textlogin=driver.find_elements_by_partial_link_text('录')[0]login.click()# 4、find_element_by_tag_nameprint(driver.find_element_by_tag_name('a'))# 5、find_element_by_class_namebutton=wait.until(EC.element_to_be_clickable((By.CLASS_NAME,'tang-pass-footerBarULogin')))button.click()# 6、find_element_by_nameinput_user=wait.until(EC.presence_of_element_located((By.NAME,'userName')))input_pwd=wait.until(EC.presence_of_element_located((By.NAME,'password')))commit=wait.until(EC.element_to_be_clickable((By.ID,'TANGRAM__PSP_10__submit')))input_user.send_keys('18611453110')input_pwd.send_keys('xxxxxx')commit.click()# 7、find_element_by_css_selectordriver.find_element_by_css_selector('#kw')# 8、find_element_by_xpath``` time.sleep(5)finally: driver.close() 二 xpath
#官网链接:http://selenium-python.readthedocs.io/locating-elements.htmlfrom selenium import webdriverfrom selenium.webdriver import ActionChainsfrom selenium.webdriver.common.by import By #按照什么方式查找,By.ID,By.CSS_SELECTORfrom selenium.webdriver.common.keys import Keys #键盘按键操作from selenium.webdriver.support import expected_conditions as ECfrom selenium.webdriver.support.wait import WebDriverWait #等待页面加载某些元素import timedriver=webdriver.PhantomJS()driver.get('https://doc.scrapy.org/en/latest/_static/selectors-sample1.html')# wait=WebDriverWait(driver,3)driver.implicitly_wait(3) #使用隐式等待try: # find_element_by_xpath #//与/ # driver.find_element_by_xpath('//body/a') # 开头的//代表从整篇文档中寻找,body之后的/代表body的儿子,这一行找不到就会报错了 driver.find_element_by_xpath('//body//a') # 开头的//代表从整篇文档中寻找,body之后的//代表body的子子孙孙 driver.find_element_by_css_selector('body a')```#取第n个res1=driver.find_elements_by_xpath('//body//a[1]') #取第一个a标签print(res1[0].text)#按照属性查找,下述三者查找效果一样res1=driver.find_element_by_xpath('//a[5]')res2=driver.find_element_by_xpath('//a[@href="image5.html"]')res3=driver.find_element_by_xpath('//a[contains(@href,"image5")]') #模糊查找print('==>', res1.text)print('==>',res2.text)print('==>',res3.text)``````#其他res1=driver.find_element_by_xpath('/html/body/p/a')print(res1.text)res2=driver.find_element_by_xpath('//a[img/@src="https://blog.csdn.net/m0_71115526/article/details/image3_thumb.jpg"]') #找到子标签img的src属性为https://blog.csdn.net/m0_71115526/article/details/image3_thumb.jpg的a标签print(res2.tag_name,res2.text)res3 = driver.find_element_by_xpath("//input[@name='continue'][@type='button']") #查看属性name为continue且属性type为button的input标签res4 = driver.find_element_by_xpath("//*[@name='continue'][@type='button']") #查看属性name为continue且属性type为button的所有标签``` ```time.sleep(5)```finally: driver.close() doc=''' Example website Name: My image 1
Name: My image 2
Name: My image 3
Name: My image 4
Name: My image 5test
Name: My image 6
'''from lxml import etreehtml=etree.HTML(doc)# html=etree.parse('search.html',etree.HTMLParser())# 1 所有节点# a=html.xpath('//*')# 2 指定节点(结果为列表)# a=html.xpath('//head')# 3 子节点,子孙节点# a=html.xpath('//p/a')# a=html.xpath('//body/a') #无数据# a=html.xpath('//body//a')# 4 父节点# a=html.xpath('//body//a[@href="image1.html"]/..')# a=html.xpath('//body//a[1]/..')# 也可以这样# a=html.xpath('//body//a[1]/parent::*')# 5 属性匹配# a=html.xpath('//body//a[@href="image1.html"]')# 6 文本获取# a=html.xpath('//body//a[@href="image1.html"]/text()')# 7 属性获取# a=html.xpath('//body//a/@href')# # 注意从1 开始取(不是从0)# a=html.xpath('//body//a[1]/@href')# 8 属性多值匹配# a 标签有多个class类,直接匹配就不可以了,需要用contains# a=html.xpath('//body//a[@]')# a=html.xpath('//body//a[contains(@class,"li")]')# a=html.xpath('//body//a[contains(@class,"li")]/text()')# 9 多属性匹配# a=html.xpath('//body//a[contains(@class,"li") or @name="items"]')# a=html.xpath('//body//a[contains(@class,"li") and @name="items"]/text()')# # a=html.xpath('//body//a[contains(@class,"li")]/text()')# 10 按序选择# a=html.xpath('//a[2]/text()')# a=html.xpath('//a[2]/@href')# 取最后一个# a=html.xpath('//a[last()]/@href')# 位置小于3的# a=html.xpath('//a[position() form > p.nav-right > p > input')button.click()import timetime.sleep(3)input_tag=browser.find_element_by_id('twotabsearchtextbox')input_tag.clear() #清空输入框input_tag.send_keys('iphone7plus')button=browser.find_element_by_css_selector('#nav-search > form > p.nav-right > p > input')button.click()# browser.close()
from selenium import webdriverfrom selenium.webdriver import ActionChainsfrom selenium.webdriver.common.by import By # 按照什么方式查找,By.ID,By.CSS_SELECTORfrom selenium.webdriver.common.keys import Keys # 键盘按键操作from selenium.webdriver.support import expected_conditions as ECfrom selenium.webdriver.support.wait import WebDriverWait # 等待页面加载某些元素import timedriver = webdriver.Chrome()driver.get('http://www.runoob.com/try/try.php?filename=jqueryui-api-droppable')wait=WebDriverWait(driver,3)# driver.implicitly_wait(3) # 使用隐式等待try: driver.switch_to.frame('iframeResult') ##切换到iframeResult sourse=driver.find_element_by_id('draggable') target=driver.find_element_by_id('droppable')```#方式一:基于同一个动作链串行执行# actions=ActionChains(driver) #拿到动作链对象# actions.drag_and_drop(sourse,target) #把动作放到动作链中,准备串行执行# actions.perform()#方式二:不同的动作链,每次移动的位移都不同``` ActionChains(driver).click_and_hold(sourse).perform() distance=target.location['x']-sourse.location['x']```track=0while track from selenium import webdriverfrom selenium.webdriver import ActionChainsfrom selenium.webdriver.common.by import By #按照什么方式查找,By.ID,By.CSS_SELECTORfrom selenium.webdriver.common.keys import Keys #键盘按键操作from selenium.webdriver.support import expected_conditions as ECfrom selenium.webdriver.support.wait import WebDriverWait #等待页面加载某些元素try: browser=webdriver.Chrome() browser.get('https://www.baidu.com') browser.execute_script('alert("hello world")') #打印警告finally: browser.close() #frame相当于一个单独的网页,在父frame里是无法直接查看到子frame的元素的,必须switch_to_frame切到该frame下,才能进一步查找from selenium import webdriverfrom selenium.webdriver import ActionChainsfrom selenium.webdriver.common.by import By #按照什么方式查找,By.ID,By.CSS_SELECTORfrom selenium.webdriver.common.keys import Keys #键盘按键操作from selenium.webdriver.support import expected_conditions as ECfrom selenium.webdriver.support.wait import WebDriverWait #等待页面加载某些元素try: browser=webdriver.Chrome() browser.get('http://www.runoob.com/try/try.php?filename=jqueryui-api-droppable')```browser.switch_to.frame('iframeResult') #切换到id为iframeResult的frame``` tag1=browser.find_element_by_id('droppable') print(tag1)```# tag2=browser.find_element_by_id('textareaCode') #报错,在子frame里无法查看到父frame的元素browser.switch_to.parent_frame() #切回父frame,就可以查找到了tag2=browser.find_element_by_id('textareaCode')print(tag2)```finally: browser.close() 七 其他
#模拟浏览器的前进后退import timefrom selenium import webdriverbrowser=webdriver.Chrome()browser.get('https://www.baidu.com')browser.get('https://www.taobao.com')browser.get('http://www.sina.com.cn/')browser.back()time.sleep(10)browser.forward()browser.close() #cookiesfrom selenium import webdriverbrowser=webdriver.Chrome()browser.get('https://www.zhihu.com/explore')print(browser.get_cookies())browser.add_cookie({'k1':'xxx','k2':'yyy'})print(browser.get_cookies())# browser.delete_all_cookies() #选项卡管理:切换选项卡,有js的方式windows.open,有windows快捷键:ctrl+t等,最通用的就是js的方式import timefrom selenium import webdriverbrowser=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(10)browser.switch_to_window(browser.window_handles[0])browser.get('https://www.sina.com.cn')browser.close() from selenium import webdriverfrom selenium.common.exceptions import TimeoutException,NoSuchElementException,NoSuchFrameExceptiontry: browser=webdriver.Chrome() browser.get('http://www.runoob.com/try/try.php?filename=jqueryui-api-droppable') browser.switch_to.frame('iframssseResult')except TimeoutException as e: print(e)except NoSuchFrameException as e: print(e)finally: browser.close() 八 项目练习
from selenium import webdriverfrom selenium.webdriver import ActionChainsfrom selenium.webdriver.common.by import By #按照什么方式查找,By.ID,By.CSS_SELECTORfrom selenium.webdriver.common.keys import Keys #键盘按键操作from selenium.webdriver.support import expected_conditions as ECfrom selenium.webdriver.support.wait import WebDriverWait #等待页面加载某些元素import timedef get_goods(driver): try: goods=driver.find_elements_by_class_name('gl-item')``` for good in goods: detail_url=good.find_element_by_tag_name('a').get_attribute('href') p_name=good.find_element_by_css_selector('.p-name em').text.replace('\n','') price=good.find_element_by_css_selector('.p-price i').text p_commit=good.find_element_by_css_selector('.p-commit a').text msg = ''' 商品 : %s 链接 : %s 价钱 :%s 评论 :%s ''' % (p_name,detail_url,price,p_commit) print(msg,end='\n\n')`````` button=driver.find_element_by_partial_link_text('下一页') button.click() time.sleep(1) get_goods(driver)except Exception: pass```def spider(url,keyword): driver = webdriver.Chrome() driver.get(url) driver.implicitly_wait(3) # 使用隐式等待 try: input_tag=driver.find_element_by_id('key') input_tag.send_keys(keyword) input_tag.send_keys(Keys.ENTER) get_goods(driver) finally: driver.close()if __name__ == '__main__': spider('https://www.jd.com/',keyword='iPhone8手机')