2017-10-14 57 views
0

當我使用硒圖書館查找相關渠道在YouTube頻道頁面長度它給了我12,但是當我使用請求庫中查找長度它給我0。我想使用請求,請給我最好的解決方案。 這裏是我的代碼,請求VS硒的Python

//Requests 

import requests 
from bs4 import BeautifulSoup 
import time 
r = requests.get("https://www.youtube.com/channel/UCoykjkkJxsz7JukJR7mGrwg/about") 
soup = BeautifulSoup(r.content, 'html.parser') 
bb = soup.find_all("ytd-mini-channel-renderer",class_="style-scope ytd-vertical-channel-section-renderer") 
print(len(bb)) 


//selenium 

from selenium import webdriver 
from bs4 import BeautifulSoup 
import time 
driver = webdriver.Chrome(chrome_path) 
driver.get("https://www.youtube.com/channel/UCoykjkkJxsz7JukJR7mGrwg/about") 
soup = BeautifulSoup(driver.page_source, 'html.parser') 
bb = soup.find_all("ytd-mini-channel-renderer",class_="style-scope ytd-vertical-channel-section-renderer") 
print(len(bb)) 

回答

0

每次我遇到這樣一個問題的時候,那是因爲JS是創造我後的數據。如果是這種情況,您可能無法使用請求,因爲它無法處理JS。

如果您在瀏覽器中導航到該YouTube頁面,則可以看到「ytd-mini-channel-renderer」存在,如果您檢查它,但是如果您查看源代碼,則會得到0個結果。您可以從「查看源代碼」中看到的代碼是請求獲得的代碼。

+0

對呀!但你知道硒與請求相比是慢的 –

+0

我想用請求 –

+0

來做這件事。不幸的是,我不認爲只有請求才可能有解決方法。一些東西必須能夠運行JavaScript。你可以嘗試使用PhantomJS,因爲它可能比Chrome更快。 – SuperStew