爬虫 之 Selenium

Selenium

准备工作:

需要预安装Chromedriver,根据Chrome浏览器的版本来选择,需要把下载好的Chromedriver.exe 放入python源目录,或者项目的目录。

驱动地址:chrome驱动地址:https://npm.taobao.org/mirrors/chromedriver

初始化操作
from selenium.webdriver import Chrome

from selenium.webdriver.common.keys import Keys#键盘操作库

web = Chrome()   #初始化浏览器

web.get("http://baidu.com")

web.quit()
基础操作:可以与xpath一起用
寻找元素:element=web.fine_element_by_xpath(xpath)#xpath在f12中直接复制xpath路径。
#找到元素后进行下一步操作:
#点击按钮:element.click()       
#填入元素:element.sen_keys()
#键盘操作:element.sen_keys(Key.ENTER)

爬取操作
.text  获取文本

get_property()  /get_attribute()获取属性
进阶操作:
爬虫时如果点击了新链接,需要我们手动设置网页跳转

web.switch_to.window(web.window_handles[-1])

web.window_handles:得到网页的窗口信息。
切换select标签:遇到标签选择的窗口时可以用
# 切换select
from selenium.webdriver.support.select import Select
sel = Select(web.find_element_by_xpath('//*[@id="OptionDate"]'))
for i in range(len(sel.options)):
    sel.select_by_index(i)  # 按照索引位置切换
    time.sleep(1)
    table = web.find_element_by_xpath('//*[@id="TableList"]/table')
iframe的处理:

iframe:在网页里面单独的一个窗口

#跳转至iframe

web.switch_to.frame()

#从iframe调回上层结构

web.switch_to.parent_frame()

隐形操作:
from selenium.webdriver.chrome.options import Options

opt = Options()
opt.add_argument("--headless")
opt.add_argument('--disable-gpu')
web = Chrome(options=opt)
二种等待方式

在我们很多时候,要等待网页的加载,如果没有加载出来,我们就运行代码,很容易出现找不到目标节点。所以我们需要自行增加等待。

  • 强制等待

    	time.sleep()
    
  • 隐式等待

    driver.implicitly_wait(30)
    

你可能感兴趣的:(爬虫,爬虫,selenium,python)