您的位置:軟件測試 > 開源軟件測試 > 開源功能測試工具 > Selenium
用selenium模擬瀏覽器點擊事件
作者:網絡轉載 發(fā)布時間:[ 2017/4/25 16:18:06 ] 推薦標簽:功能測試工具 Selenium

  開始寫爬蟲時,遇到和js有關的內容只能繞過去,盡可能翻源碼找或者模擬post之類的辦法獲得想要的內容。
  但是不是所有的post都能模擬的,或者說對于那些有很長的加密和一些莫名繁多的參數以及動不動給你返回一大堆java后端接口信息的post,分析起來成本過高。
  于是考慮模擬點擊事件不失為另一種可行的策略。
  為什么選擇selenium
  嗯,selenium是一個很好的自動化測試工具(瀏覽器)集/組件。
  可能滿足需求的還有PhantomJS和Ghost.py之類的東西,但是當我發(fā)現Ghost.py is very headless,并且 得知在Python中使用PhantomJS的一個比較好的辦法是基于selenium 后,那直接選擇selenium好了。
  selenium Python還有一份精心維護的比Ghost.py的官方文檔寫的還好的非官方文檔: 我是文檔
  關于文檔,我會告訴你前一陣我用grab這個庫,它的作者是俄羅斯人以至于很多的troubleshooting和issue都是俄文,我差點學會俄語了好嗎。
  一份簡短的代碼
  selenium.webdriver有好多種實現,下面是一個選擇Chromedriver的實現方式,包括禁止加載圖片等設置。
  總的來說用起來還是很方便的
  import time
  import pymongo
  from selenium import webdriver
  from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
  from selenium.common.exceptions import NoSuchElementException
  class Crawler(object):
  def __init__(self):
  # selenium and webdriver settings
  # ignore the img
  chromeOptions = webdriver.ChromeOptions()
  prefs = {"profile.managed_default_content_settings.images":2}
  chromeOptions.add_experimental_option("prefs",prefs)
  website = 'your website'
  self.driver = webdriver.Chrome('your chromedriver location', chrome_options=chromeOptions)
  # mongo settings
  client = pymongo.MongoClient("localhost", 27017)
  db = client.your_db
  self.table = db.your_table
  # start
  self.driver.get(website)
  def crawl(self):
  while True:
  # refresh
  self.driver.delete_all_cookies()
  self.driver.refresh()
  # possibly without decoy
  try:
  self.driver.find_element_by_class_name('decoy').click()
  except NoSuchElementException:
  pass
  time.sleep(1)
  # question
  question = self.driver.find_element_by_class_name('wrapper').text
  # current word
  word = question.split(' ')[1]
  # choices
  choices = [i.value_of_css_property('background-image').split('(')[1].split(')')[0] for i in self.driver.find_element_by_class_name('choices').find_elements_by_tag_name('a')]
  # .......
  if __name__ == '__main__':
  Crawler().crawl()

上一頁12下一頁
軟件測試工具 | 聯系我們 | 投訴建議 | 誠聘英才 | 申請使用列表 | 網站地圖
滬ICP備07036474 2003-2017 版權所有 上海澤眾軟件科技有限公司 Shanghai ZeZhong Software Co.,Ltd