一、选项卡
from selenium.webdriver import Chrome
from bs4 import BeautifulSoup
b = Chrome()
进入网站
b.get(‘https://kns.cnki.net/’)
获取搜索框并输入内容进入网页
b.find_element_by_id('txt_search').send_keys('数据分析\n')
获取所有数据对应的标签
name_a_list =b.find_element_by_css_selector('.result-table-list .fz14')
点击进入详情页
name_a_list.click()
切换选项卡,让浏览器对象指向第二个页面
b.switch_to.window(b.window_handles[-1])
获取第二页数据
soup = BeautifulSoup(b.page_source,'lxml')
关闭第二个页面,回到第一个页面
b.close()
b.switch_to.window(b.window_handles[0])
若没有产生新的页面,点击前进或者后退切换页面
b.back() - 后退
b.forward() - 前进
二、滚动
1)滚动的js代码window,scrollBy(x偏移量,y偏移量)x 左正右负,y下正上负
2)js标签对象.scrollBy(x偏移量,y偏移量) - 让指定标签的内容滚动
js获取标签的方法:
document.getElementById(id属性值) - 获取id属性值为指定的标签,返回标签对象
document.getElementByClassName(class属性值) - 获取class属性值为指定值的标签值,返回一个列表,列表中的元素是标签
三、等待
1.隐式等待
b.implicitly_wait(5)
2.显示等待 - 等待某个条件成立或者不成立时就执行代码
使用方法:
1)创建等待对象:WebDriverWait(浏览器对象,超时时间)
2)添加等待条件:
等待对象.until(条件) - 等到指定条件成立,代码才接着往后执行
等待对象.until_not(条件) - 等到指定条件不成立,代码才接着往后执行
3)常用条件
presence_of_element_located(标签) - 某一个标签出现为止
visibility_of_element_located(标签) - 当指定标签可见
text_to_be_present_in_element(标签,值) - 当指定标签的标签内容包含指定值
text_to_be_present_in_element_value(标签,值) - 当指定标签的value属性值为指定值的时候
注意:标签的写法:(By.获取标签方式,数据)
例如:(By,ID,‘key’)
(By.CSS_SELECTOR,'#p1 a
四、基本配置
from selenium.webdriver import Chrome,ChromeOptions
options = ChromeOptions()
1.取消测试环境 的显示
options.add_experimental_option('excludeSwitches', ['enable-automation'])
2.取消图片加载
options.add_experimental_option("prefs", {"profile.managed_default_content_settings.images": 2})