Python爬虫——Selenium库

本文介绍了Selenium库在Python爬虫中的应用,主要用于解决JavaScript渲染问题。内容包括Selenium的基本使用,如声明浏览器对象、访问页面、查找元素、元素交互操作等,并详细讲解了隐式等待和显式等待的实现。此外,还涵盖了异常处理和其他高级功能,如动作链、JavaScript执行、Frame操作、Cookies管理及选项卡管理。
摘要由CSDN通过智能技术生成

一、介绍

自动化测试工具,支持多种浏览器。

爬虫主要用来解决JavaScript渲染的问题。

二、用法

基本使用

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait

browser = webdriver.Chrome()
try:
	browser.get('https://www.baidu.com')
	input = browser.find_element_by_id('kw')
	input.send_keys('Python')
	input.send_keys('Key.ENTER')
	wait = WebDriverWait(browser,10)
	wait.until(EC.presence_of_element_located(By.ID,'content_left'))
	print(browser.current_url)
	print(browser.get_cookies())
	print(browser.page_source)
finally:
	browser.close()

申明浏览器对象

from selenium import webdriver
browser = webdriver.Chrome()#谷歌
browser = webdriver.Firefox()#火狐
browser = webdriver.Edge()
browser = webdriver.PhantomJS()
browser = webdriver.Safari()

访问页面

from selenium import webdriver
browser = webdriver.Chrome()#谷歌
browser.get("https://www.taobao.com")
print(browser.page_source)
browser.close()

查找元素

from selenium import webdriver
browser = webdriver.Chrome()
browser.get('https://www.taobao.com')
input_first = browser.find_element_by_id('q')
input_second = browser.find_element_by_css_selector('#q')
input_third = browser.find_element_by_xpath('//*[@id="q"]')
print(input_first,input_second,input_third)
browser.close()
from selenium import webdriver
from selenium.webdriver.common.by import By
browser = webdriver.Chrome()
browser.get('https://www.taobao.com')
input_first = browser.find_element(By.ID,'q')
print(input_first)
browser.close()
find_element_by_name
find_element_by_xpath
find_element_by_link_text
find_element_by_partial_link_text
find_element_by_tag_name
find_element_by_class_name
find_element_by_css_selector

多个元素

from selenium import webdriver
browser = webdriver.Chrome()
browser.get('https://www.taobao.com')
lis = browser.find_elements_by_css_selector('.service-bd li')
print(lis)
browser.close()
from selenium import webdriver
from selenium.webdriver.common.by import By
browser = webdriver.Chrome()
browser.get('https://www.taobao.com')
lis = browser.find_element(By.CSS_SELECTOR,'.service-bd li')
print(lis)
browser.close()
find_elements_by_name
find_elements_by_xpath
find_elements_by_link_text
find_elements_by_partial_link_text
find_elements_by_tag_name
find_elements_by_class_name
find_elements_by_css_selector
元素交互操作

对获取的元素调用交互方法

from selenium import webdriver
import time
browser = webdriver.Chrome()
browser.get('https://www.taobao.com')
input = browser.find_element_by_id('q')
input.send_keys("iPhone")
time.sleep(1)
input.clear()
input.send_keys("iPad")
button = browser.find_elements_by_class_name('btn-search')
button.click()
交互动作

将动作附加到动作链中串行执行

from selenium import webdriver
from selenium.webdriver import ActionChains
browser = webdriver.Chrome()
url = "http://www.runoob.com/try/try.php?filename=jqueryui-api-droppable"
browser.get(url)
browser.switch_to_frame('iframeResult')
source = browser.find_element_by_css_selector("#draggable")
target = browser.find_element_by_css_selector("#droppable")
actions = ActionChains(browser)
actions.drag_and_drop(source,target)
actions.perform()

执行JavaScript

from selenium import webdriver
browser = webdriver.Chrome()
browser.get("https://www.zhihu.com")
browser.execute_script('window.scrollTo(0,document.body.scrollHeight)')
browser.execute_script('alert("To Bottom")')
获取元素信息

获取属性

from selenium import webdriver
from selenium.webdriver import ActionChains
browser = webdriver.Chrome()
url = 'https://www.zhihu.com/explore'
browser.get(url)
logo = browser.find_element_by_id('zh-top-link-logo')
print(logo)
print(logo.get_attribute('class'))

获取文本值

from selenium import webdriver
browser = webdriver.Chrome()
url = 'https://www.zhihu.com/explore'
browser.get(url)
input = browser.find_element_by_class_name('zu-top-add-question')
print(input.text)

获取ID,位置,标签名,大小

from selenium import webdriver
browser = webdriver.Chrome()
url = 'https://www.zhihu.com/explore'
browser.get(url)
input = browser.find_element_by_class_name('zu-top-add-question')
print(input.id)
print(input.location)
print(input.tag_name)
print(input.size)

Frame

import time
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium import webdriver
browser = webdriver.Chrome()
url = 'http://www.runoob.com/try/try.php?filename=jqueryui-api-droppable'
browser.get(url)
browser.switch_to.frame('iframeResult')
source = browser.find_element_by_css_selector('#draggable')
print(source)
try:
	logo = browser.find_element_by_class_name('logo')
except NoSuchElementException:
	print("NO Logo")
browser.switch_to.parent_frame()
logo = browser.find_element_by_class_name('logo')
print(logo)
print(logo.text)
等待

隐式等待

当使用了隐式等待执行测试的时候,如果WebDriver没有在DOM中找到元素,将继续等待,超出设定时间后则抛出找不到元素异常,换句话说,当查找元素或元素并没有立即出现的时候,隐式等待将等待一段时间再查找DOM,默认时间是0.

from selenium import webdriver
browser = webdriver.Chrome()
browser.implicitlu_wait(10)
browser.get("https://www.zhihu.com/explore")
input = browser.find_element_by_class_name('zu-top-add-question')
print(input)

显式等待

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
browser = webdriver.Chrome()
browser.get("https://www.taobao.com")
wait = WebDriverWait(browser,10)
input = wait.until(EC.persence_of_element_located((By.ID,'q')))
button = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR,'.btn-search')))
print(input,button)
title_is #标题是某内容
title_contains#标题包含某内容
presence_of_element_located#元素加载出,传入定位元组,如(By.Id,'q')
visibility_of_element_located#可见元素,传入定位元组
visibility_of#可见,传入元素对象
presence_of_all_element_located#所有元素加载出
text_tobe_present_in_element#某个元素文本包含某文字
text_tobe_present_in_element_value #某个元素值包含某文字
frame_to_be_available_and_switch_to_it frame加载并切换
invisibility_of_element_located#元素不可见
element_to_be_clickable#元素可点击
staleness_of#判断一个元素是否仍在DOM,可判断页面是否已经刷新
element_to_be_selected#元素可选择,传递元素对象
element_located_to_be_selected#元素可选择,传入定位元组
element_selection_state_to_be#传入元素对象以及状态,相等返回True,否则返回Flase
element_located_selection_state_to_be#传入定位元组以及状态,相等返回True,否则返回Flase
alert_is_present#是否出现Alert

前进后退

import time
from selenium import webdriver
browser = webdriver.Chrome()
browser.get('https://www.baidu.com')
browser.get('https://www.taobao.com')
browser.get('https://www.python.org')
browser.back()
time.sleep(1)
browser.forward()
browser.close()

Cookies

from selenium import webdriver
browser = webdriver.Chrome()
browser.get('https://www.zhihu.com/explore')
print(browser.get_cookies)
browser.add_cookies({'name':'name','domain':'www.zhihu.com','value':'germey'})
print(browser.get_cookies)
browser.delete_all_cookies()
print(browser.get_cookies())

选项卡管理

from selenium import webdriver
browser = 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(1)
browser.switch_to_window(browser.window_handles[0])
browser.get('https://python.org')
异常处理
from selenium import webdriver
browser = webdriver.Chrome()
browser.get('https://www.baidu.com')
browser.find_element_by_id('hello')#错误的请求,无异常处理
from selenium import webdriver
from selenium.common.exceptions import TimeoutException,NoSuchElementException
browser = webdriver.Chrome()
try:#有异常处理
	browser.get('https://www.baidu.com')
except TimeoutException:
	print('Time Out')
try:
	browser.find_element_by_id('hello')
except NoSuchElementException:
	print('No Element')
finally:
	browser.close()

更多操作:http://selenium-python.readthedocs.io/api.html


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值