# selenium: 自动化测试,模拟人类与浏览器的交互行为
# 环境搭建 pip install selenium
# 下载浏览器驱动 到python安装目录 我的C:\Program Files\python
from selenium.webdriver import Chrome
# 1.创建浏览器对象
web = Chrome()
web.get("http://www.baidu.com")
print(web.title)
爬取拉钩网
from selenium.webdriver import Chrome
# 导入按钮
from selenium.webdriver.common.keys import Keys
import time
import csv
web = Chrome()
web.get("http://lagou.com")
# web.find_element_by~~~
# 找到元素
el = web.find_element_by_xpath('//*[@id="changeCityBox"]/p[1]/a')
el.click()
"""
注意:可能在点击后页面数据还没有加载出来,程序就运行到
input = web.find_element_by_xpath('//*[@id="search_input"]').send_keys("python", Keys.ENTER)
可能会报错,一般存在 ajax 中
解决:time sleep(1)
"""
# 找到输入框,输入,点击搜索
web.find_element_by_xpath('//*[@id="search_input"]').send_keys("python", Keys.ENTER)
# divs = web.find_element_by_xpath('//*[@id="jobList"]/div[1]/div')
time.sleep(1)
divs = web.find_elements_by_class_name("item__10RTO")
# print(divs)
"""
div: //*[@id="jobList"]/div[1]/div
岗位名称://*[@id="openWinPostion"]
发布时间://*[@id="jobList"]/div[1]/div[1]/div[1]/div[1]/span/div/div[1]
//*[@id="jobList"]/div[1]/div[1]
薪资://*[@id="jobList"]/div[1]/div[1]/div[1]/div[1]/span/div/div[2]/span
公司://*[@id="jobList"]/div[1]/div[1]/div[1]/div[2]/div[1]/a
"""
f = open("../file/sel操作.csv", mode="w", encoding="utf-8", newline='')
csvWriter = csv.writer(f)
for div in divs:
job_name = div.find_element_by_xpath('//*[@id="openWinPostion"]').text
job_price = div.find_element_by_xpath('./div[1]/div[1]/div[2]/span').text
job_company = div.find_element_by_xpath('./div[1]/div[2]/div[1]/a').text
# with csvWriter.writerow([job_name, job_price, job_company]) as c:
csvWriter.writerow([job_name, job_price, job_company])
# print(job_name, "\t", job_price, job_company)