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的语句构造,可以参看上一篇博客 ,“先抓大,后抓小,寻找循环点”
未完待续
文章来源: https://blog.csdn.net/qq_35159009/article/details/90522384