1、说明
selenium是一个强大的python库,他可以用几行代码,控制浏览器,做出自动打开、输入、点击等操作,就像是有一个真正的用户在操作一样。
安装:
windows:pip install selenium
mac:pip3 install selenium
另外,selenium的脚本可以控制所有常见浏览器的操作,在使用之前,需要安装浏览器的驱动。推荐使用Chrome浏览器,下面有一个链接可以下载,下载之后解压,将其中的.exe文件复制到python安装目录下就可以了。
http://chromedriver.storage.googleapis.com/index.html
这里下载之后放一份到python的安装目录中去
2、Example(视觉感受)
这是一段python小课提供的案例。
# 本地Chrome浏览器设置方法
from selenium import webdriver #从selenium库中调用webdriver模块
import time
driver = webdriver.Chrome() # 设置引擎为Chrome,真实地打开一个Chrome浏览器
driver.get('https://localprod.pandateacher.com/python-manuscript/hello-spiderman/') # 打开网页
time.sleep(2)
teacher = driver.find_element_by_id('teacher')
teacher.send_keys('必须是吴枫呀')
assistant = driver.find_element_by_name('assistant')
assistant.send_keys('都喜欢')
time.sleep(1)
button = driver.find_element_by_class_name('sub')
time.sleep(1)
button.click()
time.sleep(1)
driver.close()
首先引入眼帘的是【你好,蜘蛛侠!】几个大字,一秒之后,它会自动跳转到一个新的页面,请你输入最喜欢的老师和助教,你点击提交之后,它又会跳转到Python之禅的中英对照页面。
3、解析与提取数据
与前面静态网页解析数据BeautifulSoup一样,Selenium库也具备解析数据,提取数据的能力。
首先不同的selenium所解析提取的,是Elements中的所有数据,而BeautifulSoup所解析的则只是Network中第0个请求的响应。
方法 | 作用 |
---|---|
find_element_by_tag_name | 通过元素的标签名称选择 |
find_element_by_class_name | 通过元素的classs属性选择 |
find_element_by_id | 通过元素的id选择 |
find_element_by_name | 通过元素的name属性选择 |
find_element_by_link_text | 通过链接文本获取超链接 |
find_element_by_partial_link_text | 通过连接的部分文本获取超链接 |
举例说明 |
find_element_by_tag_name:通过元素的名称选择
# 如<h1>你好,蜘蛛侠!</h1>
# 可以使用find_element_by_tag_name('h1')
find_element_by_class_name:通过元素的class属性选择
# 如<h1 class="title">你好,蜘蛛侠!</h1>
# 可以使用find_element_by_class_name('title')
find_element_by_id:通过元素的id选择
# 如<h1 id="title">你好,蜘蛛侠!</h1>
# 可以使用find_element_by_id('title')
find_element_by_name:通过元素的name属性选择
# 如<h1 name="hello">你好,蜘蛛侠!</h1>
# 可以使用find_element_by_name('hello')
#以下两个方法可以提取出超链接
find_element_by_link_text:通过链接文本获取超链接
# 如<a href="spidermen.html">你好,蜘蛛侠!</a>
# 可以使用find_element_by_link_text('你好,蜘蛛侠!')
find_element_by_partial_link_text:通过链接的部分文本获取超链接
# 如<a href="https://localprod.pandateacher.com/python-manuscript/hello-spiderman/">你好,蜘蛛侠!</a>
# 可以使用find_element_by_partial_link_text('你好')
提取出来的element(元素)与tag对象类似
WebElement | Tag | 作用 |
---|---|---|
WebElement.text | Tag.text | 提取文字 |
WebElement.get_attribute() | Tag[] | 输入参数:属性名,提取属性值 |
总结即是: | ||
使用find_element_by 寻找元素的方法仅仅是找到了第一个满足条件的元素,与BeautifulSoup的find_all一样,selenium寻找所有满足要求的方法是find_elements_by 增加一个s 。 |
4、Selenium与BeautiSoup配合工作
其实BeautifulSoup解析的就是网页的源代码,我们可以通过将源代码字符串提取出来给到BS解析即可。
HTML源代码字符串 = driver.page_source
5、自动操作浏览器的方法
.send_keys('') #模拟按键输入,自动填写表单
.click() # 点击元素
.slear() # 清除元素的内容
6、静默模式设置
最后简单将一句,一般做爬虫时我们并不想看到浏览器的操作,只需要得到最后的结果就好,这时就需要设置浏览器的静默模式了。
# 本地Chrome浏览器的静默默模式设置:
from selenium import webdriver #从selenium库中调用webdriver模块
from selenium.webdriver.chrome.options import Options # 从options模块中调用Options类
chrome_options = Options() # 实例化Option对象
chrome_options.add_argument('--headless') # 把Chrome浏览器设置为静默模式
driver = webdriver.Chrome(options = chrome_options) # 设置引擎为Chrome,在后台默默运行