Python怎么爬取动态网页——如何使用selenium和PhantomJS

版权声明:本文为博主原创文章,如需转载请声明文件出处。 https://blog.csdn.net/qq_39530754/article/details/82534209

一、selenium和PhantomJS用法简介

selenium是web的自动化测试工具,类似按键精灵,可以直接运行在浏览器上。

pip install selenium


PhantomJS是基于webkit的无界面浏览器,使用时,无需输入header等。

需要从 phantomjs.org处下载,再将bin目录添加到环境变量path中。

1.1 基本使用流程

"""基本流程"""
from selenium import webdriver
 
#要想调用键盘操作需要引入keys包
from selenium.webdriver.common.keys import Keys
 
#调用环境变量指定的PhantomJS浏览器创建浏览器对象
driver = webdriver.PhantomJS()
#如果没有在环境变量指定PhantomJS位置
#driver = webdriver.PhantomJS(executable_path="F:\phantomjs\phantomjs-2.1.1-windows\bin")
 
#get方法会一直等到页面被完全加载,然后才会继续程序
#通常测试会在这里选择time.sleep(2)
driver.get("http://www.baidu.com")
 
'''具体的操作,仿人为上网'''
 
#关闭当前网页,如果只有一个页面,会关闭浏览器
#driver.close()
 
#关闭浏览器
driver.quit()

1.2 网页信息显示

"""网页信息"""
#打印页面标题“百度一下,你就知道”
str_ = driver.title
 
#获取当前网页的源代码
str_html = driver.page_source
 
#获取当前网页的cookie
cookies = driver.get_cookies()
cookies['name']
cookies['value']
 
#获取当前网页的url
str_ = driver.current_url

 1.3 键盘操作

"""键盘操作"""
#要想调用键盘操作需要引入keys包
from selenium.webdriver.common.keys import Keys
 
#获取页面名为wrapper的id标签的文本内容
data = driver.find_element_by_id("wrapper").text
#除了by_id之外,还有by_name, by_xpath, by_class_name等
#其中,element选取的是一个,elements选出的是全部。
#这个类似bs4
 
#生成当前页面的快照并保存
driver.save_screenshot("baidu.png")
 
#id="su"是百度搜索按钮,click()是模拟点击
driver.find_element_by_id("su").click()
#click之后需要等待几秒,等待网页响应。
time.sleep(2)
driver.save_screenshot("click.png")
 
#id="kw"是百度搜索输入框,输入字符串“长城”
driver.find_element_by_id("kw").send_keys(u"长城")
driver.save_screenshot("input.png")
 
#ctrl+a全选输入框
driver.find_element_by_id("kw").send_keys(Keys.CONTROL, 'a')
 
#模拟ENTER回车键
driver.find_element_by_id("kw").send_keys(Keys.RETURN)
 
#清空输入框
driver.find_element_by_id("kw").clear()

 1.4 鼠标操作

"""鼠标操作"""
#导入类
from selenium.webdriver import ActionChains
 
#鼠标移动到某个位置
ac = driver.find_element_by_xpath('element')
ActionChains(driver).move_to_element(ac).perform()
 
#单击,(操作鼠标,移到某处,点击,显示效果)
ac = driver.find_element_by_xpath('element')
ActionChains(driver).move_to_element(ac).click(ac).perform()
#或者可以driver.find_element_by_xpath('element').click()
 
#双击
ac = driver.find_element_by_xpath('element')
ActionChains(driver).move_to_element(ac).double_click(ac).perform()
 
#右击
ac = driver.find_element_by_xpath('element')
ActionChains(driver).move_to_element(ac).context_click(ac).perform()

1.5 其他操作

 
"""执行JavaScript语句"""

js='document.body.scrollTop=10000'#向下滚动10000像素

driver.execute_script(js)

猜你喜欢

转载自blog.csdn.net/qq_39530754/article/details/82534209
今日推荐