您现在的位置是:首页 > 文章详情

selenium+PhantomJS+IP代理

日期:2019-07-22点击:601

首先安装selenium、PhantomJS

  • selenium安装

    pip install selenium
  • PhantomJS安装
    这个需要手动的到官网下载

开始使用

  • 导入需要的包

    import random from selenium import webdriver from selenium.webdriver.common.proxy import ProxyType # 调用键盘按键操作 from selenium.webdriver.common.keys import Keys # 调用鼠标操作 from selenium.webdriver import ActionChains # 设置请求头 from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
  • 操作PhantomJS

    desired_cap = DesiredCapabilities.PHANTOMJS.copy() # 设置请求头 desired_cap['phantomjs.page.settings.User-Agent'] = 'user_agent...' # 配置代理IP proxy = [ '--proxy=%s' % "139.199.38.177:8118", # 设置的代理ip '--proxy-type=http', # 代理类型 '--ignore-ssl-errors=true', ] # 启动PhantomJS driver = webdriver.PhantomJS(executable_path="./phantomjs-2.1.1-linux-x86_64/bin/phantomjs", desired_capabilities=desired_cap, service_args=proxy) # 设置屏幕大小 driver.set_window_size(800, 600) # 请求网页 driver.get("http://www.baidu.com/") # 根据html元素的id找到搜索框,并且输入要搜索的内容 driver.find_element_by_id('kw').send_keys("时光不写博客") # 查到搜索按钮,并且点击搜索 random.choice([ # 使用鼠标点击操作 driver.find_element_by_id('su').click(), # 使用键盘回车操作 driver.find_element_by_id('su').send_keys(Keys.RETURN) ]) # 截屏 driver.save_screenshot('baidu.png') # 使用xpath查到标签,并且点击 driver.find_elements_by_xpath("//div[@id=%s]/h3/a" % 2)[0].click() # 拿到当前浏览器的最后一个tab,这是一个列表的形式 tab = driver.window_handles[-1] # 切换到刚刚点击的页面 driver.switch_to_window(tab) driver.save_screenshot('blog.png') # 根据标签名查到要点击的数据 title = driver.find_element_by_tag_name("title") # 移动鼠标到title的位置,并且点击 ActionChains(driver).move_to_element(title).click(title).perform() # 刷新页面 driver.refresh() # 打印页面源码 driver.page_source title = driver.find_elements_by_xpath("//a[@href='/.']")[0] # 移动到title下10像素位置,并且双点击 ActionChains(driver).move_to_element_with_offset(title, 0, 10).double_click().perform() # 退出 driver.quit()
  • 具体操作命令
命令 说明
click(on_element=None) 单击鼠标左键
context_click(on_element=None) 点击鼠标右键
double_click(on_element=None) 双击鼠标左键
click_and_hold(on_element=None) 点击鼠标左键,不松开
drag_and_drop(source, target) 拖拽到某个元素然后松开
drag_and_drop_by_offset(source, xoffset, yoffset) 拖拽到某个坐标然后松开
key_down(value, element=None) 按下某个键盘上的键
key_up(value, element=None) 松开某个键
move_by_offset(xoffset, yoffset) 鼠标从当前位置移动到某个坐标
move_to_element(to_element) 鼠标移动到某个元素
move_to_element_with_offset(to_element, xoffset, yoffset) 移动到距某个元素(左上角坐标)多少距离的位置
perform() 执行链中的所有动作
release(on_element=None) 在某个元素位置松开鼠标左键
send_keys(*keys_to_send) 发送某个键到当前焦点的元素
send_keys_to_element(element, *keys_to_send) 发送某个键到指定元素

本文链接:时光不写博客-selenium+PhantomJS+IP代理

原文链接:https://yq.aliyun.com/articles/710445
关注公众号

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。

持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。

转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。

文章评论

共有0条评论来说两句吧...

文章二维码

扫描即可查看该文章

点击排行

推荐阅读

最新文章