3.selenium模块
本节内容:
- 介绍
- 安装
- 基本使用
- 选择器
- 等待元素被加载
- 元素交互操作
- 其他
- 项目练习
一.介绍
1 selenium最初是一个自动化测试工具,而爬虫中使用它主要是为了解决requests无法直接执行JavaScript代码的问题 2 3 selenium本质是通过驱动浏览器,完全模拟浏览器的操作,比如跳转、输入、点击、下拉等,来拿到网页渲染之后的结果,可支持多种浏览器 4 5 from selenium import webdriver 6 browser=webdriver.Chrome() 7 browser=webdriver.Firefox() 8 browser=webdriver.PhantomJS() 9 browser=webdriver.Safari() 10 browser=webdriver.Edge()
二.安装
1 #安装:selenium+chromedriver 2 pip3 install selenium 3 下载chromdriver.exe放到python安装路径的scripts目录中即可,注意最新版本是2.35,并非2.9 4 国内镜像网站地址:http://npm.taobao.org/mirrors/chromedriver/2.35/ 5 最新的版本去官网找:https://sites.google.com/a/chromium.org/chromedriver/downloads 6 7 #验证安装 8 C:\Users\Administrator>python3 9 Python 3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 18:41:36) [MSC v.1900 64 bit (AMD64)] on win32 10 Type "help", "copyright", "credits" or "license" for more information. 11 >>> from selenium import webdriver 12 >>> driver=webdriver.Chrome() #弹出浏览器 13 >>> driver.get('https://www.baidu.com') 14 >>> driver.page_source 15 16 #注意: 17 selenium3默认支持的webdriver是Firfox,而Firefox需要安装geckodriver 18 下载链接:https://github.com/mozilla/geckodriver/releases
1 #安装:selenium+phantomjs 2 pip3 install selenium 3 下载phantomjs,解压后把phantomjs.exe所在的bin目录放到环境变量 4 下载链接:http://phantomjs.org/download.html 5 6 #验证安装 7 C:\Users\Administrator>phantomjs 8 phantomjs> console.log('egon gaga') 9 egon gaga 10 undefined 11 phantomjs> ^C 12 C:\Users\Administrator>python3 13 Python 3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 18:41:36) [MSC v.1900 64 bit (AMD64)] on win32 14 Type "help", "copyright", "credits" or "license" for more information. 15 >>> from selenium import webdriver 16 >>> driver=webdriver.PhantomJS() #无界面浏览器 17 >>> driver.get('https://www.baidu.com') 18 >>> driver.page_source
三.基本使用
1 from selenium import webdriver 2 from selenium.webdriver import ActionChains 3 from selenium.webdriver.common.by import By #按照什么方式查找,By.ID,By.CSS_SELECTOR 4 from selenium.webdriver.common.keys import Keys #键盘按键操作 5 from selenium.webdriver.support import expected_conditions as EC 6 from selenium.webdriver.support.wait import WebDriverWait #等待页面加载某些元素 7 8 browser=webdriver.Chrome() 9 try: 10 browser.get('https://www.baidu.com') 11 12 input_tag=browser.find_element_by_id('kw') 13 input_tag.send_keys('美女') #python2中输入中文错误,字符串前加个u 14 input_tag.send_keys(Keys.ENTER) #输入回车 15 16 wait=WebDriverWait(browser,10) 17 wait.until(EC.presence_of_element_located((By.ID,'content_left'))) #等到id为content_left的元素加载完毕,最多等10秒 18 19 print(browser.page_source) 20 print(browser.current_url) 21 print(browser.get_cookies()) 22 23 finally: 24 browser.close()
四.选择器
1.基本用法
1 #官网链接:http://selenium-python.readthedocs.io/locating-elements.html 2 from selenium import webdriver 3 from selenium.webdriver import ActionChains 4 from selenium.webdriver.common.by import By #按照什么方式查找,By.ID,By.CSS_SELECTOR 5 from selenium.webdriver.common.keys import Keys #键盘按键操作 6 from selenium.webdriver.support import expected_conditions as EC 7 from selenium.webdriver.support.wait import WebDriverWait #等待页面加载某些元素 8 import time 9 10 driver=webdriver.Chrome() 11 driver.get('https://www.baidu.com') 12 wait=WebDriverWait(driver,10)#显式等待 13 14 try: 15 #===============所有方法=================== 16 # 1、find_element_by_id 17 # 2、find_element_by_link_text 18 # 3、find_element_by_partial_link_text 19 # 4、find_element_by_tag_name 20 # 5、find_element_by_class_name 21 # 6、find_element_by_name 22 # 7、find_element_by_css_selector 23 # 8、find_element_by_xpath 24 # 强调: 25 # 1、上述均可以改写成find_element(By.ID,'kw')的形式 26 # 2、find_elements_by_xxx的形式是查找到多个元素,结果为列表 27 28 #===============示范用法=================== 29 # 1、find_element_by_id 30 print(driver.find_element_by_id('kw')) 31 32 # 2、find_element_by_link_text 33 # login=driver.find_element_by_link_text('登录') 34 # login.click() 35 36 # 3、find_element_by_partial_link_text#模糊搜索 37 login=driver.find_elements_by_partial_link_text('录')[0] 38 login.click() 39 40 # 4、find_element_by_tag_name 41 print(driver.find_element_by_tag_name('a')) 42 43 # 5、find_element_by_class_name 44 button=wait.until(EC.element_to_be_clickable((By.CLASS_NAME,'tang-pass-footerBarULogin'))) 45 button.click() 46 47 # 6、find_element_by_name 48 input_user=wait.until(EC.presence_of_element_located((By.NAME,'userName'))) 49 input_pwd=wait.until(EC.presence_of_element_located((By.NAME,'password'))) 50 commit=wait.until(EC.element_to_be_clickable((By.ID,'TANGRAM__PSP_10__submit'))) 51 52 input_user.send_keys('18611453110') 53 input_pwd.send_keys('lhf@094573') 54 commit.click() 55 56 # 7、find_element_by_css_selector 57 driver.find_element_by_css_selector('#kw') 58 59 # 8、find_element_by_xpath 60 61 time.sleep(5) 62 63 finally: 64 driver.close()
2.xpath
1 #官网链接:http://selenium-python.readthedocs.io/locating-elements.html 2 from selenium import webdriver 3 from selenium.webdriver import ActionChains 4 from selenium.webdriver.common.by import By #按照什么方式查找,By.ID,By.CSS_SELECTOR 5 from selenium.webdriver.common.keys import Keys #键盘按键操作 6 from selenium.webdriver.support import expected_conditions as EC 7 from selenium.webdriver.support.wait import WebDriverWait #等待页面加载某些元素 8 import time 9 10 driver=webdriver.PhantomJS() 11 driver.get('https://doc.scrapy.org/en/latest/_static/selectors-sample1.html') 12 # wait=WebDriverWait(driver,3) 13 driver.implicitly_wait(3) #使用隐式等待 14 15 try: 16 # find_element_by_xpath 17 #//与/ 18 # driver.find_element_by_xpath('//body/a') # 开头的//代表从整篇文档中寻找,body之后的/代表body的儿子,这一行找不到就会报错了 19 20 driver.find_element_by_xpath('//body//a') # 开头的//代表从整篇文档中寻找,body之后的//代表body的子子孙孙 21 driver.find_element_by_css_selector('body a') 22 23 #取第n个 24 res1=driver.find_elements_by_xpath('//body//a[1]') #取第一个a标签 25 print(res1[0].text) 26 27 #按照属性查找,下述三者查找效果一样 28 res1=driver.find_element_by_xpath('//a[5]') 29 res2=driver.find_element_by_xpath('//a[@href="image5.html"]') 30 res3=driver.find_element_by_xpath('//a[contains(@href,"image5")]') #模糊查找 31 print('==>', res1.text) 32 print('==>',res2.text) 33 print('==>',res3.text) 34 35 36 #其他 37 res1=driver.find_element_by_xpath('/html/body/div/a') 38 print(res1.text) 39 40 res2=driver.find_element_by_xpath('//a[img/@src="image3_thumb.jpg"]') #找到子标签img的src属性为image3_thumb.jpg的a标签 41 print(res2.tag_name,res2.text) 42 43 res3 = driver.find_element_by_xpath("//input[@name='continue'][@type='button']") #查看属性name为continue且属性type为button的input标签 44 res4 = driver.find_element_by_xpath("//*[@name='continue'][@type='button']") #查看属性name为continue且属性type为button的所有标签 45 46 47 time.sleep(5) 48 49 finally: 50 driver.close() 51 52 #xpath可以直接用页面的检查元素copy到
3.获取标签属性
1 from selenium import webdriver 2 from selenium.webdriver import ActionChains 3 from selenium.webdriver.common.by import By #按照什么方式查找,By.ID,By.CSS_SELECTOR 4 from selenium.webdriver.common.keys import Keys #键盘按键操作 5 from selenium.webdriver.support import expected_conditions as EC 6 from selenium.webdriver.support.wait import WebDriverWait #等待页面加载某些元素 7 8 browser=webdriver.Chrome() 9 10 browser.get('https://www.amazon.cn/') 11 12 wait=WebDriverWait(browser,10) 13 wait.until(EC.presence_of_element_located((By.ID,'cc-lm-tcgShowImgContainer'))) 14 15 tag=browser.find_element(By.CSS_SELECTOR,'#cc-lm-tcgShowImgContainer img') 16 17 #获取标签属性, 18 print(tag.get_attribute('src')) 19 20 21 #获取标签ID,位置,名称,大小(了解) 22 print(tag.id) 23 print(tag.location) 24 print(tag.tag_name) 25 print(tag.size) 26 27 28 browser.close()
五.等待元素被加载
1 #1、selenium只是模拟浏览器的行为,而浏览器解析页面是需要时间的(执行css,js),一些元素可能需要过一段时间才能加载出来,为了保证能查找到元素,必须等待 2 3 #2、等待的方式分两种: 4 隐式等待:在browser.get('xxx')前就设置,针对所有元素有效 5 显式等待:在browser.get('xxx')之后设置,只针对某个元素有效
1 from selenium import webdriver 2 from selenium.webdriver import ActionChains 3 from selenium.webdriver.common.by import By #按照什么方式查找,By.ID,By.CSS_SELECTOR 4 from selenium.webdriver.common.keys import Keys #键盘按键操作 5 from selenium.webdriver.support import expected_conditions as EC 6 from selenium.webdriver.support.wait import WebDriverWait #等待页面加载某些元素 7 8 browser=webdriver.Chrome() 9 10 #隐式等待:在查找所有元素时,如果尚未被加载,则等10秒 11 browser.implicitly_wait(10) 12 13 browser.get('https://www.baidu.com') 14 15 16 input_tag=browser.find_element_by_id('kw') 17 input_tag.send_keys('美女') 18 input_tag.send_keys(Keys.ENTER) 19 20 contents=browser.find_element_by_id('content_left') #没有等待环节而直接查找,找不到则会报错 21 print(contents) 22 23 browser.close()
1 from selenium import webdriver 2 from selenium.webdriver import ActionChains 3 from selenium.webdriver.common.by import By #按照什么方式查找,By.ID,By.CSS_SELECTOR 4 from selenium.webdriver.common.keys import Keys #键盘按键操作 5 from selenium.webdriver.support import expected_conditions as EC 6 from selenium.webdriver.support.wait import WebDriverWait #等待页面加载某些元素 7 8 browser=webdriver.Chrome() 9 browser.get('https://www.baidu.com') 10 11 12 input_tag=browser.find_element_by_id('kw') 13 input_tag.send_keys('美女') 14 input_tag.send_keys(Keys.ENTER) 15 16 17 #显式等待:显式地等待某个元素被加载 18 wait=WebDriverWait(browser,10) 19 wait.until(EC.presence_of_element_located((By.ID,'content_left'))) 20 21 contents=browser.find_element(By.CSS_SELECTOR,'#content_left') 22 print(contents) 23 24 25 browser.close()
六.元素交互操作
1 from selenium import webdriver 2 from selenium.webdriver import ActionChains 3 from selenium.webdriver.common.by import By #按照什么方式查找,By.ID,By.CSS_SELECTOR 4 from selenium.webdriver.common.keys import Keys #键盘按键操作 5 from selenium.webdriver.support import expected_conditions as EC 6 from selenium.webdriver.support.wait import WebDriverWait #等待页面加载某些元素 7 8 browser=webdriver.Chrome() 9 browser.get('https://www.amazon.cn/') 10 wait=WebDriverWait(browser,10) 11 12 13 input_tag=wait.until(EC.presence_of_element_located((By.ID,'twotabsearchtextbox'))) 14 input_tag.send_keys('iphone 8') 15 button=browser.find_element_by_css_selector('#nav-search > form > div.nav-right > div > input') 16 button.click() 17 18 19 import time 20 time.sleep(3) 21 22 input_tag=browser.find_element_by_id('twotabsearchtextbox') 23 input_tag.clear() #清空输入框 24 input_tag.send_keys('iphone7plus') 25 button=browser.find_element_by_css_selector('#nav-search > form > div.nav-right > div > input') 26 button.click() 27 28 29 30 # browser.close()
1 from selenium import webdriver 2 from selenium.webdriver import ActionChains 3 from selenium.webdriver.common.by import By # 按照什么方式查找,By.ID,By.CSS_SELECTOR 4 from selenium.webdriver.common.keys import Keys # 键盘按键操作 5 from selenium.webdriver.support import expected_conditions as EC 6 from selenium.webdriver.support.wait import WebDriverWait # 等待页面加载某些元素 7 import time 8 9 driver = webdriver.Chrome() 10 driver.get('http://www.runoob.com/try/try.php?filename=jqueryui-api-droppable') 11 wait=WebDriverWait(driver,3) 12 # driver.implicitly_wait(3) # 使用隐式等待 13 14 try: 15 driver.switch_to.frame('iframeResult') ##切换到iframeResult 16 sourse=driver.find_element_by_id('draggable') 17 target=driver.find_element_by_id('droppable') 18 19 #方式一:基于同一个动作链串行执行 20 # actions=ActionChains(driver) #拿到动作链对象 21 # actions.drag_and_drop(sourse,target) #把动作放到动作链中,准备串行执行 22 # actions.perform() 23 24 #方式二:不同的动作链,每次移动的位移都不同 25 ActionChains(driver).click_and_hold(sourse).perform() 26 distance=target.location['x']-sourse.location['x'] 27 28 track=0 29 while track < distance: 30 ActionChains(driver).move_by_offset(xoffset=2,yoffset=0).perform() 31 track+=2 32 33 ActionChains(driver).release().perform() 34 35 time.sleep(10) 36 37 finally: 38 driver.close()
1 from selenium import webdriver 2 from selenium.webdriver import ActionChains 3 from selenium.webdriver.common.by import By #按照什么方式查找,By.ID,By.CSS_SELECTOR 4 from selenium.webdriver.common.keys import Keys #键盘按键操作 5 from selenium.webdriver.support import expected_conditions as EC 6 from selenium.webdriver.support.wait import WebDriverWait #等待页面加载某些元素 7 8 9 try: 10 browser=webdriver.Chrome() 11 browser.get('https://www.baidu.com') 12 browser.execute_script('alert("hello world")') #打印警告 13 finally: 14 browser.close()
1 #frame相当于一个单独的网页,在父frame里是无法直接查看到子frame的元素的,必须switch_to_frame切到该frame下,才能进一步查找 2 3 from selenium import webdriver 4 from selenium.webdriver import ActionChains 5 from selenium.webdriver.common.by import By #按照什么方式查找,By.ID,By.CSS_SELECTOR 6 from selenium.webdriver.common.keys import Keys #键盘按键操作 7 from selenium.webdriver.support import expected_conditions as EC 8 from selenium.webdriver.support.wait import WebDriverWait #等待页面加载某些元素 9 10 11 try: 12 browser=webdriver.Chrome() 13 browser.get('http://www.runoob.com/try/try.php?filename=jqueryui-api-droppable') 14 15 browser.switch_to.frame('iframeResult') #切换到id为iframeResult的frame 16 17 tag1=browser.find_element_by_id('droppable') 18 print(tag1) 19 20 # tag2=browser.find_element_by_id('textareaCode') #报错,在子frame里无法查看到父frame的元素 21 browser.switch_to.parent_frame() #切回父frame,就可以查找到了 22 tag2=browser.find_element_by_id('textareaCode') 23 print(tag2) 24 25 finally: 26 browser.close()
七.其他
1 #模拟浏览器的前进后退 2 import time 3 from selenium import webdriver 4 5 browser=webdriver.Chrome() 6 browser.get('https://www.baidu.com') 7 browser.get('https://www.taobao.com') 8 browser.get('http://www.sina.com.cn/') 9 10 browser.back() 11 time.sleep(10) 12 browser.forward() 13 browser.close()
1 #cookies 2 from selenium import webdriver 3 4 browser=webdriver.Chrome() 5 browser.get('https://www.zhihu.com/explore') 6 print(browser.get_cookies()) 7 browser.add_cookie({'k1':'xxx','k2':'yyy'}) 8 print(browser.get_cookies()) 9 10 # browser.delete_all_cookies()
1 #选项卡管理:切换选项卡,有js的方式windows.open,有windows快捷键:ctrl+t等,最通用的就是js的方式 2 import time 3 from selenium import webdriver 4 5 browser=webdriver.Chrome() 6 browser.get('https://www.baidu.com') 7 browser.execute_script('window.open()') 8 9 print(browser.window_handles) #获取所有的选项卡 10 browser.switch_to_window(browser.window_handles[1]) 11 browser.get('https://www.taobao.com') 12 time.sleep(10) 13 browser.switch_to_window(browser.window_handles[0]) 14 browser.get('https://www.sina.com.cn') 15 browser.close()
1 from selenium import webdriver 2 from selenium.common.exceptions import TimeoutException,NoSuchElementException,NoSuchFrameException 3 4 try: 5 browser=webdriver.Chrome() 6 browser.get('http://www.runoob.com/try/try.php?filename=jqueryui-api-droppable') 7 browser.switch_to.frame('iframssseResult') 8 9 except TimeoutException as e: 10 print(e) 11 except NoSuchFrameException as e: 12 print(e) 13 finally: 14 browser.close()
1 #注意:网站都策略都是在不断变化的,精髓在于学习流程。下述代码生效与2017-11-7,不能保证永久有效 2 from selenium import webdriver 3 from selenium.webdriver import ActionChains 4 from selenium.webdriver.common.by import By 5 from selenium.webdriver.common.keys import Keys 6 from selenium.webdriver.support import expected_conditions as EC 7 from selenium.webdriver.support.wait import WebDriverWait 8 9 browser=webdriver.Chrome() 10 11 try: 12 browser.get('http://mail.163.com/') 13 14 wait=WebDriverWait(browser,5) 15 16 frame=wait.until(EC.presence_of_element_located((By.ID,'x-URS-iframe'))) 17 browser.switch_to.frame(frame) 18 19 wait.until(EC.presence_of_element_located((By.CSS_SELECTOR,'.m-container'))) 20 21 inp_user=browser.find_element_by_name('email') 22 inp_pwd=browser.find_element_by_name('password') 23 button=browser.find_element_by_id('dologin') 24 inp_user.send_keys('18611453110') 25 inp_pwd.send_keys('xxxx') 26 button.click() 27 28 #如果遇到验证码,可以把下面一小段打开注释 29 # import time 30 # time.sleep(10) 31 # button = browser.find_element_by_id('dologin') 32 # button.click() 33 34 wait.until(EC.presence_of_element_located((By.ID,'dvNavTop'))) 35 write_msg=browser.find_elements_by_css_selector('#dvNavTop li')[1] #获取第二个li标签就是“写信”了 36 write_msg.click() 37 38 39 wait.until(EC.presence_of_element_located((By.CLASS_NAME,'tH0'))) 40 recv_man=browser.find_element_by_class_name('nui-editableAddr-ipt') 41 title=browser.find_element_by_css_selector('.dG0 .nui-ipt-input') 42 recv_man.send_keys('378533872@qq.com') 43 title.send_keys('圣旨') 44 print(title.tag_name) 45 46 47 frame=wait.until(EC.presence_of_element_located((By.CLASS_NAME,'APP-editor-iframe'))) 48 browser.switch_to.frame(frame) 49 body=browser.find_element(By.CSS_SELECTOR,'body') 50 body.send_keys('egon很帅,可以加工资了') 51 52 browser.switch_to.parent_frame() #切回他爹 53 send_button=browser.find_element_by_class_name('nui-toolbar-item') 54 send_button.click() 55 56 #可以睡时间久一点别让浏览器关掉,看看发送成功没有 57 import time 58 time.sleep(10000) 59 60 except Exception as e: 61 print(e) 62 finally: 63 browser.close()
1 from selenium import webdriver 2 from selenium.webdriver import ActionChains 3 from selenium.webdriver.common.by import By #按照什么方式查找,By.ID,By.CSS_SELECTOR 4 from selenium.webdriver.common.keys import Keys #键盘按键操作 5 from selenium.webdriver.support import expected_conditions as EC 6 from selenium.webdriver.support.wait import WebDriverWait #等待页面加载某些元素 7 import time 8 9 10 def get_goods(driver): 11 try: 12 goods=driver.find_elements_by_class_name('gl-item') 13 14 for good in goods: 15 detail_url=good.find_element_by_tag_name('a').get_attribute('href') 16 17 p_name=good.find_element_by_css_selector('.p-name em').text.replace('\n','') 18 price=good.find_element_by_css_selector('.p-price i').text 19 p_commit=good.find_element_by_css_selector('.p-commit a').text 20 21 msg = ''' 22 商品 : %s 23 链接 : %s 24 价钱 :%s 25 评论 :%s 26 ''' % (p_name,detail_url,price,p_commit) 27 28 print(msg,end='\n\n') 29 30 31 button=driver.find_element_by_partial_link_text('下一页') 32 button.click() 33 time.sleep(1) 34 get_goods(driver) 35 except Exception: 36 pass 37 38 def spider(url,keyword): 39 driver = webdriver.Chrome() 40 driver.get(url) 41 driver.implicitly_wait(3) # 使用隐式等待 42 try: 43 input_tag=driver.find_element_by_id('key') 44 input_tag.send_keys(keyword) 45 input_tag.send_keys(Keys.ENTER) 46 get_goods(driver) 47 finally: 48 driver.close() 49 50 51 if __name__ == '__main__': 52 spider('https://www.jd.com/',keyword='iPhone8手机')