1.從知乎話題入手,避免登錄
從話題入手,避免知乎登錄,比如我們需要的是“心理學”話題數據,只要輸入網址
https://www.zhihu.com/topic/19551432/top-answers,就能進入,閱讀話題,而不需要登錄知乎。
2.話題界面研究
進入話題,看到下圖所示界面。我們需要爬取的是,“心理學”話題的所有多層子話題、所有精華內容的題目、詳細內容、以及所有標籤
注意,頁面只展示了部分子話題,需要全部,還需登錄。
在Chrome瀏覽器中,在想了解的頁面或段落上右鍵,點擊“檢查”,使用開發者工具,可以瞭解頁面結構。
我們首先想要爬取展示的所有子話題,所以,要了解子話題的網頁地址在哪,以及名稱在哪。這裏選中元素——點擊右鍵——copy——Xpath,可以直接使用xpath來找到頁面元素,準則爲“先抓大,後抓小,尋找循環點”。
也可以自己構造xpath語句。
通過分析可知,所有的a(子話題)都在
網址都在herf中,名稱都在div中
3.正式爬蟲獲取子話題
def topic_select(url):
topics=DataFrame(list(topic.find()))['key'] #mongodb數據庫的存儲內容,可以不使用
driver = webdriver.PhantomJS()
driver.get(url) #url就是https://www.zhihu.com/topic/19551432/top-answers
#//*[@id="root"]/div/main/div/div[2]/div/div/div/div[2]/div
#//*[@id="root"]/div/main/div/div[2]/div/div/div/div[2]/div/div[2]/div[2]/a[1]
infos = driver.find_elements_by_xpath('//*[@class="Card-section"]/div[2]/div[2]/a')
for info in infos:
url_c=info.get_attribute('href') #子話題網址
key=info.find_element_by_xpath('div/div/div/span').text #子話題名稱
#topic.update({'key':key},{'$set':{"url":url}})
if key not in str(topics): #防止重複
topic.insert_one({'key':key,'url':url})
try:
topic_select(url_c) #循環,獲取所有層次的子話題
except:
pass
driver.quit()
未完待續