您的位置:軟件測(cè)試 > 開(kāi)源軟件測(cè)試 > 開(kāi)源功能測(cè)試工具 > Selenium
用selenium模擬瀏覽器點(diǎn)擊事件
作者:網(wǎng)絡(luò)轉(zhuǎn)載 發(fā)布時(shí)間:[ 2017/4/25 16:18:06 ] 推薦標(biāo)簽:功能測(cè)試工具 Selenium

  開(kāi)始寫(xiě)爬蟲(chóng)時(shí),遇到和js有關(guān)的內(nèi)容只能繞過(guò)去,盡可能翻源碼找或者模擬post之類的辦法獲得想要的內(nèi)容。
  但是不是所有的post都能模擬的,或者說(shuō)對(duì)于那些有很長(zhǎng)的加密和一些莫名繁多的參數(shù)以及動(dòng)不動(dòng)給你返回一大堆java后端接口信息的post,分析起來(lái)成本過(guò)高。
  于是考慮模擬點(diǎn)擊事件不失為另一種可行的策略。
  為什么選擇selenium
  嗯,selenium是一個(gè)很好的自動(dòng)化測(cè)試工具(瀏覽器)集/組件。
  可能滿足需求的還有PhantomJS和Ghost.py之類的東西,但是當(dāng)我發(fā)現(xiàn)Ghost.py is very headless,并且 得知在Python中使用PhantomJS的一個(gè)比較好的辦法是基于selenium 后,那直接選擇selenium好了。
  selenium Python還有一份精心維護(hù)的比Ghost.py的官方文檔寫(xiě)的還好的非官方文檔: 我是文檔
  關(guān)于文檔,我會(huì)告訴你前一陣我用grab這個(gè)庫(kù),它的作者是俄羅斯人以至于很多的troubleshooting和issue都是俄文,我差點(diǎn)學(xué)會(huì)俄語(yǔ)了好嗎。
  一份簡(jiǎn)短的代碼
  selenium.webdriver有好多種實(shí)現(xiàn),下面是一個(gè)選擇Chromedriver的實(shí)現(xiàn)方式,包括禁止加載圖片等設(shè)置。
  總的來(lái)說(shuō)用起來(lái)還是很方便的
  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()

上一頁(yè)12下一頁(yè)
軟件測(cè)試工具 | 聯(lián)系我們 | 投訴建議 | 誠(chéng)聘英才 | 申請(qǐng)使用列表 | 網(wǎng)站地圖
滬ICP備07036474 2003-2017 版權(quán)所有 上海澤眾軟件科技有限公司 Shanghai ZeZhong Software Co.,Ltd