1.知乎動態加載
當我們需要爬取知乎中的數據時,會發現知乎採取動態加載技術,內容塊只有在瀏覽器下滾時纔會刷新。沒有“下一頁”,所以不同與普通爬蟲,我們需要模擬瀏覽器的操作。
2.Selenium與PhantomJS的配合
對於採用異步加載技術的網頁,可以使用Selenium模塊模擬瀏覽器。Selenium是一個用於Web應用程序測試的工具,直接運行在瀏覽器中,使瀏覽器自動加載頁面,Selenium自身不帶瀏覽器,需要配合第三方瀏覽器來使用。PhantomJS是一種無界面,“無頭”瀏覽器,開銷小,速度快。
通過Selenium與PhantomJS的配合使用,不需要進行逆向工程,便可獲得異步加載數據,能夠完全模擬用戶在瀏覽器的所有操作,包括輸入框的內容填寫、單擊、截屏、下滑等。
3.模擬下滾應對動態加載
def scroll_foot(driver):
if driver.name == "chrome" or driver.name == 'phantomjs':
js = "var q=document.body.scrollTop=100000"
elif driver.name == 'internet explorer':
js = "var q=document.documentElement.scrollTop=100000"
return driver.execute_script(js)
注意一定是100000啊,之前少了個0,差點被坑死
#獲取子頁面網址
def get_info(url):
driver = webdriver.PhantomJS()
#driver.keep_alive = False
driver.get(url)
#driver.implicitly_wait(1)
for i in range(500):
scroll_foot(driver)
time.sleep(2)
#//*[@id="TopicMain"]/div[3]/div/div/div/div[1]
infos = driver.find_elements_by_xpath('//*[@id="TopicMain"]/div[3]/div/div/div/div')
for info in infos:
try:
#//*[@id="TopicMain"]/div[3]/div/div/div/div[1]/div/h2/div/a
questions=info.find_elements_by_xpath('div/h2/div/a')
for question in questions:
question=question.get_attribute('href')
#print(question)
#full_question='https://www.zhihu.com'+question
#print(full_question) 自動加
psy.insert_one({'url':question}) #mongodb數據庫插入
#get_question_info(question)
driver.close
except IndexError :
pass
driver.quit()
此處的url可以是https://www.zhihu.com/topic/19551432/hot
並且,使用模擬瀏覽器,就不用再加網頁頭了。
xpath的語句構造,可以參看上一篇博客 ,“先抓大,後抓小,尋找循環點”
未完待續