python网络爬虫边看边学(selenium模块一)

selenium模块

一、安装并设置

       1、安装

       pip install selenium

       2、安装浏览器驱动

       这里提供谷歌浏览器驱动下载,chrome驱动地址:https://npm.taobao.org/mirrors/chromedriver

找到适合本机浏览器的版本号下载。

       下载的驱动可以放在项目里,也可以放在python解释器所在的文件夹。

from selenium.webdriver import Chrome  # 导入谷歌浏览器类

# 创建浏览器对象(浏览器驱动放在了解释器文件夹)
# driver=Chrome()

# 浏览器驱动放在了项目里
driver = Chrome(executable_path='chromedriver')

driver.get('https://www.baidu.com')  # 输入网址
print(driver.title)  # 打印title

  

二、selenium简单应用

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

web = Chrome()

web.get('http://lagou.com')
# 找到某个元素,点击
el = web.find_element_by_xpath('//*[@id="changeCityBox"]/p[1]/a')
# 点击事件
el.click()

time.sleep(1)  # 让浏览器缓一会儿

# 找到输入框,输入python 回车
web.find_element_by_xpath('//*[@id="search_input"]').send_keys("python", Keys.ENTER)

time.sleep(1)
# 查找存放数据的位置,进行数据提取
# 找到页面中存放数据的所有的li
li_list = web.find_elements_by_xpath('//*[@id="s_position_list"]/ul/li')
for li in li_list:
    job_name = li.find_element_by_tag_name("h3").text
    job_comp = li.find_element_by_xpath("./div/div[2]/div/a").text
    job_price = li.find_element_by_xpath("./div/div/div[2]/div/span").text
    print(job_name, job_comp, job_price)

  

三、selenium实现窗口切换

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

web = Chrome()
web.get('http://lagou.com')

web.find_element_by_xpath('//*[@id="cboxClose"]').click()
time.sleep(1)

web.find_element_by_xpath('//*[@id="search_input"]').send_keys('python', Keys.ENTER)
time.sleep(1)

web.find_element_by_xpath('//*[@id="s_position_list"]/ul/li[1]/div[1]/div[1]/div[1]/a/h3').click()

# 进入新窗口提取
# 在selenium中,新窗口默认不会切换,要手工切换
web.switch_to.window(web.window_handles[-1])
job_detail = web.find_element_by_xpath('//*[@id="job_detail"]/dd[2]/div').text
print(job_detail)

# 关闭子窗口
web.close()
# 变更selenium的窗口视角,回到原来的窗口
web.switch_to.window(web.window_handles[0])

  iframe切换

web = Chrome()
web.get("https://www.91kanju.com/vod-play/541-2-1.html")
# 找到那个iframe
iframe = web.find_element_by_xpath('//*[@id="player_iframe"]')
web.switch_to.frame(iframe)
val =web.find_element_by_xpath('/html/body/div[4]').get_attribute("value")
print(val)

  打开58同城,输入关键字“兼职”,打开搜索到的第一条记录,下载职位简介。

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

web = Chrome()

web.get('https://jintan.58.com/')

web.find_element_by_xpath('//*[@id="keyword"]').send_keys("兼职", Keys.ENTER)

time.sleep(1)

web.find_element_by_xpath('/html/body/div[3]/div[1]/div[5]/div[1]/div[1]/div[1]/div[1]/h2/a').click()

web.switch_to.window(web.window_handles[-1])
time.sleep(1)
text = web.find_element_by_xpath('//*[@id="content"]/div[1]/div[2]/p[2]').text
web.close()
print(text)

  

 

 

posted @ 2021-04-12 08:39  wangshanglinju  阅读(63)  评论(0编辑  收藏  举报