今天爬取的是騰訊視頻的最新短評(鬼吹燈之黃皮子墳)的評論者、最新短評內容、評論贊;
首先分析一下要爬取的網頁
首次加載出的最新短評
點擊更多,看下url是否會變化
點擊加載更多之后
由此看出應該是動態加載的
其實剛開始我還看了這些數據是json,還想著用構造url,直接請求的方法去爬,但是看完請求url就放棄了;
Paste_Image.png
Paste_Image.png
這里url有太多的參數不好構造就沒有往這方面想了;
下面進入正題,
首先pip安裝selenium
下面是代碼
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
import time
import pymongo
# 連接到Mongo
conn = pymongo.MongoClient(host='localhost', port=27017)
# 選擇或創建數據庫
tencent = conn['tencent']
# 選擇或創建數據集合
newsdata = tencent['鬼吹燈之黃皮子墳']
# 把每個評論的數據存入這個字典
comment_one = {}
# 使用Chrome瀏覽器模擬打開網頁,但是要把下載的chromedriver.exe放在python的文件路徑下,
#調試好之后換成PhantomJs,速度應該會快一點
driver = webdriver.Chrome()
driver.get("https://v.qq.com/tv/p/topic/gcdzhpzf/index.html")
# 下拉滑動瀏覽器屏幕,具體下拉多少根據自己實際情況決定
driver.execute_script("window.scrollBy(0,10000)")
time.sleep(8)
driver.execute_script("window.scrollBy(0,6000)")
time.sleep(3)
i = 0
# 這里必須要先切到你要爬取數據的frame下,否則找不到你寫的路徑
driver.switch_to.frame('commentIframe1')
# 這里我用的是find_elements_by_xpath匹配的元素,個人比較喜歡用xpath匹配,比較簡單方便
comments_name = driver.find_elements_by_xpath(
'//div[@class="np-post-header"]/span[1]/a[1]')
comments_content = driver.find_elements_by_xpath(
'//div[@id="allComments"]//div[@class="np-post-content"]')
comments_vote = driver.find_elements_by_xpath(
'//div[@class="np-post-footer"]/a[1]/em')
print("第%s頁" % i)
#存入字典
for comment_name, comment_content, comment_vote in zip(
comments_name[-10: ], comments_content[-10: ], comments_vote[-10: ]):
comment_one = {
'評論者': comment_name.text,
'評論內容': comment_content.text,
'評論贊': comment_vote.text
}
# 把數據插入數據庫
newsdata.insert_one(comment_one)
#下面是爬取多頁的評論數據,同上
while driver.find_element_by_xpath('//div[@id="loadMore"]').text == '加載更多':
page_a = len(comments_name)
driver.find_element_by_xpath('//div[@id="loadMore"]').click()
time.sleep(5)
driver.execute_script("window.scrollBy(0,6000)")
time.sleep(3)
comments_name = driver.find_elements_by_xpath(
'//div[@class="np-post-header"]/span[1]/a[1]')
comments_content = driver.find_elements_by_xpath(
'//div[@id="allComments"]//div[@class="np-post-content"]')
comments_vote = driver.find_elements_by_xpath(
'//div[@class="np-post-footer"]/a[1]/em')
page_b = len(comments_name)
i += 1
print("第%s頁" % i)
for comment_name, comment_content, comment_vote in zip(
comments_name[page_a:page_b], comments_content[page_a:page_b], comments_vote[page_a:page_b]):
comment_one = {
'評論者': comment_name.text,
'評論內容': comment_content.text,
'評論贊': comment_vote.text
}
newsdata.insert_one(comment_one)
運行結果:大概爬了4000多條評論,應該沒有丟失的
Paste_Image.png
這里有幾點注意一下:
1、爬取多頁的最新短評,元素的匹配是否正常,雖然方法很多,因為這里相同名字元素太多了;
2、選擇列表的數據,這里首頁是10個,點擊一次加載更多是20條評論,但是你打開json數據key看到有些數據不知道為什么是空的,在網頁上沒有展示出來的,可能是有些評論異常吧,所以這里如果是固定的每次累加20個取數據的話,取出的數據應該是有問題的,
最后,大家有什么好的方法可以評論建議一下,多謝