未分类

说明selenium是一个自动化测试工具,而爬虫中使用它主要是为了解决requests无法执行javaScript代码的问题。优点通过驱动浏览器,完全模拟浏览器的操作,比如跳转、输入、点击、下拉等…进而拿到网页渲染之后的结果,可支持多种浏览器,真正做到可见及可爬。缺点使用selenium本质上是驱动浏览器对目标站点发送请求,那浏览器在访问目标站点的时候,需要把静态资源都加载完毕,比如html、css、js这些文件,加载完成后,等待浏览器执行,最后呈现在页面。所以用它的坏处就是效率极低!所以我们一般用它来做登录验证,Js特别复杂,没有必要去解密的场景等。使用下载驱动以谷歌浏览器为例驱动下载地址:http://chromedriver.storage.googleapis.com/index.html找到本机安装的谷歌浏览器,与之对应的版本。(虽然驱动是32位,但是支持64位浏览器的)基本使用打开大数据男孩网站fromseleniumimportwebdriver#驱动的路径bro=webdriver.Chrome(executable_path="./chromedriver_win32/chromedriver.exe")#打开这个网址bro.get(url="https://bigdataboy.cn/")找到搜索按钮,并点击fromseleniumimportwebdriver#驱动的地址bro=webdriver.Chrome(executable_path="./chromedriver_win32/chromedriver.exe")bro.get(url="https://bigdataboy.cn/")#找到搜索按钮search_tab=bro.find_element_by_xpath('//span[@class="icon-search"]')#点击搜索按钮search_tab.click()输入搜索内容在输入内容之前,需要判断内容是否加载完成,给出的判断方案是:定时去某个标签,如果该标签存在了,则认为页面加载完成。fromseleniumimportwebdriver#驱动的地址bro=webdriver.Chrome(executable_path="./chromedriver_win32/chromedriver.exe")bro.get(url="https://bigdataboy.cn/")#找到搜索按钮search_tab=bro.find_element_by_xpath('//span[@class="icon-search"]')#点击搜索按钮search_tab.click()fromselenium.webdriver.common.byimportByfromselenium.webdriver.supportimportexpected_conditionsasECfromselenium.webdriver.support.uiimportWebDriverWait"""判断搜索页面的记载情况1.默认0.5秒判断一次。Wait()里poll_frequency参数设置2.判断标签的方法有:ID、NAME、CLASS_NAME、XPATH、TAG_NAME、LINK_TEXT、PARTIAL_LINK_TEXT、CSS_SELECTOR"""#60秒没有检测到id为keyword的标签表示,加载失败WebDriverWait(bro,60).until(EC.presence_of_element_located((By.ID,"keyword")))#找到输入框input_tab=bro.find_element_by_xpath('//input[@id="keyword"]')#输入值input_tab.send_keys("大数据男孩")#关闭浏览器#bro.close()

2020-4-19 1047 0