selenium切换浏览器选项卡
以“中国知网”为例
from selenium.webdriver import Chrome
from selenium.webdriver.common.by import By
import time
# 1.创建浏览器
b = Chrome()
# 2.打开中国知网
b.get('https://www.cnki.net/')
# 3.获取输入框输入’数据分析‘
search = b.find_element(By.ID, 'txt_SearchText')
search.send_keys('数据分析\n') # \n表示按下回车
time.sleep(1) # 暂停1秒
# 4.获取搜索结果中所有论文的标题标签
titles = b.find_elements(By.CLASS_NAME, 'fz14') # 注意是获取多页,b.find_elements (只获取一页是b.find_element)
# print(titles)
# 点击第一个搜索结果
# titles[0].click()
# time.sleep(1) # 暂停1秒
# 切换选项卡,让浏览器对象指向详情页
# b.window_handles() # 获取当前存在的所有窗口选显卡
b.switch_to.window(b.window_handles[-1]) # 将擦护给你扣切换到最后一个窗口页面
# 获取详情页数据
print(b.page_source)
# 关闭当前窗口
b.close() # b指向哪个页面就关闭哪个页面
# 将选项卡切换回第一个页面
b.switch_to.window(b.window_handles[0])
# 点击下一页获取内容
titles[1].click()
# 全流程
from selenium.webdriver import Chrome
from selenium.webdriver.common.by import By
import time
from bs4 import BeautifulSoup
def analysis_data(html):
soup = BeautifulSoup(html, 'lxml')
digest = soup.select_one('#ChDivSummary').text
print(digest)
def get_net_data():
# 1.创建浏览器
b = Chrome()
# 2.打开中国知网
b.get('https://www.cnki.net/')
# 3.获取输入框,输入"数据分析"
search = b.find_element(By.ID, 'txt_SearchText')
search.send_keys('数据分析\n')
time.sleep(1)
for _ in range(3): # 获取3页数据
# 4.获取搜索结果所有论文的标题标签
titles = b.find_elements(By.CLASS_NAME, 'fz14')
for x in titles:
# 点击一个搜索结果
x.click()
time.sleep(1)
# 切换选项卡,让浏览器对象指向详情页
b.switch_to.window(b.window_handles[-1])
# 获取详情页数据, 解析数据
# print(b.page_source)
analysis_data(b.page_source)
# 关闭当前窗口
b.close()
# 将选项卡切换回第一个页面
b.switch_to.window(b.window_handles[0])
print('--------------------一页数据获取完成--------------------------')
b.find_element(By.ID, 'PageNext').click()
time.sleep(4)
input()
if __name__ == '__main__':
get_net_data()