# 爬取拉勾网信息,用selenium模块

from selenium.webdriver import Chrome
from selenium.webdriver.common.keys import Keys
import time

web = Chrome()  # 创建浏览器,打开拉勾网
web.get("https://www.lagou.com/")
# 找到城市选择窗口的关闭按钮,并点击
web.find_element_by_xpath('//*[@id="cboxClose"]').click()
# 找到搜索输入框,输入“python”,回车
time.sleep(1)  # 延时等待网页加载,太快出错
web.find_element_by_xpath('//*[@id="search_input"]').send_keys('python', Keys.ENTER)
# 搜索到的各个链接的信息文本,检查看到是在h3标签内,上个节点标签是class值为“position_link”的a标签
alist = web.find_elements_by_class_name("position_link")
for a in alist:
    # a.find_element_by_tag_name("h3").click() # 此语句会出错,提示元素点击被拦截
    # 只能用下面两条语句代替
    element = web.find_element_by_tag_name("h3")
    web.execute_script("arguments[0].click();", element)
    # 切换到链接窗口
    web.switch_to_window(web.window_handles[-1])
    # 打印子窗口文本信息
    print(web.find_element_by_xpath('//*[@id="job_detail"]').text)
    web.close() # 链接窗口关闭,回到主窗口
    web.switch_to_window(web.window_handles[0])
    time.sleep(1)