1. 程式人生 > >使用python+selenium製作瀏覽器爬蟲,徹底解決ajax非同步載入問題(待更新)

使用python+selenium製作瀏覽器爬蟲,徹底解決ajax非同步載入問題(待更新)

開啟瀏覽器需要下載相應的webdriver並儲存到系統path下。chrome對應的webdriver下載地址:http://download.csdn.net/detail/u013760453/9790569

from selenium import webdriver

from selenium.webdriver.common.keys import Keys
browser=webdriver.Chrome()#開啟chrome
browser.get(r'http://icrm.baidu.com/')#開啟網頁
elem = browser.find_element_by_xpath('//*[@id="user"]')#by後面可選的型別有id/name/value等等

elem.click()#點選按鈕
# elem.send_keys(Keys.RETURN)#模擬回車鍵

# browser.back()#頁面前進後退
# browser.forward()

# print(browser.page_source)#獲取載入後的html
# browser.quit()#關閉瀏覽器

填寫內容:獲取element後使用elem.send_keys('***')

xpath的獲取:在頁面元件上右鍵-檢查-在html相應標籤上右鍵-copy-copy xpath

#document下的非同步載入內容的選取
原網址:http://stackoverflow.com/questions/24360135/python-selenium-webdriver-finding-document-element

使用如下程式碼後即可使相關內容可選
iframe = browser.find_element_by_css_selector('iframe')
browser.switch_to.frame(iframe)


#向codeMirror程式碼編輯器中填寫程式碼,該xpath應為包含codemirror整體的類的xpath,不可以是各個細分codemirror元件的xpath
elem = browser.find_element_by_xpath('//*[@id="b6_up"]/div/form/div[1]/div')
browser.execute_script("arguments[0].CodeMirror.setValue(arguments[1]);",elem,"test")

# 組合鍵CTRL+ENTER
# browser.find_element_by_xpath('//*[@id="b7_execute"]').send_keys(Keys.CONTROL,Keys.ENTER)