我想抓取這個網站https://lens.zhihu.com/api/v4/videos/1123764263738900480來獲取play_url使用 Python。
這個網站有一個非常快速的重定向,并且 url 沒有改變。原play_url頁面中的 無效,如果你想訪問它,你會看到“你沒有權限...”。所以我time.sleep(10)在程式中使用來處理重定向(這似乎不適用于請求)。
(我犯了一個錯誤,我看到的重定向程序可能只是我的Firefox瀏覽器自動渲染JSON代碼。但我提到的方法確實可以處理重定向。)
但正如我在1.txt程式中看到的,抓取的內容沒有play_url我想要的,并且其中的 url 仍然無效。
這是play_url我想要的,可以在標簽中的瀏覽器檢查器中看到a,其class值為url:image
這是我使用的代碼:
import time
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
service = Service(executable_path='C:\\Users\\X\\chromedriver_win32\\chromedriver.exe')
options = Options()
options.add_experimental_option('excludeSwitches', ['enable-logging'])
options.add_argument("--headless")
options.add_argument('user-agent="Mozilla/5.0"')
driver = webdriver.Chrome(service=service, options=options)
driver.get('https://lens.zhihu.com/api/v4/videos/1123764263738900480')
time.sleep(10)
pageSource = driver.page_source
driver.quit()
bs = BeautifulSoup(pageSource, 'html.parser')
with open('C:\\Users\\X\\Desktop\\1.txt', 'a', encoding='utf-8') as file:
file.write(f"{bs}")
play_url = bs.find('a', {'class': 'url'}).get("title")
print(play_url)
它回傳:
Traceback (most recent call last):
File "c:\Users\X\Desktop\Handle redirect\stackoverflow.py", line 22, in <module>
play_url = bs.find('a', {'class': 'url'}).get("title")
AttributeError: 'NoneType' object has no attribute 'get'
('a', {'class': 'url'})所以在抓取的內容中,我在瀏覽器檢查器中沒有看到。
為什么抓取的內容與我在瀏覽器 Inspector 中看到的內容不同以及如何處理?
編輯:感謝 Martin Evans 的評論,現在我知道瀏覽器從源代碼處理 Javascript,因此它看起來與源代碼不同。但就我而言,我在開發者工具網路中看不到任何 js 鏈接。實際上,只有兩個鏈接:image。所以我仍然不知道上面的問題。
更新:感謝@Sarhan 的評論,我解決了這個問題。我以前使用 Firefox,即使標簽不存在,瀏覽器也會自動呈現源代碼。我在 Edge 中嘗試了 url,結果如下:image,只是我從服務器獲取的 JSON 代碼,根本沒有('a', {'class': 'url'})。此外,非常感謝@Dimitar,所以我可以獲得play_url。
uj5u.com熱心網友回復:
您可以使用 Requests 從該 url 獲取回應并提取 play_url。
import requests
url = "https://lens.zhihu.com/api/v4/videos/1123764263738900480"
headers = {
"Accept": "text/html,application/xhtml xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.82 Safari/537.36"
}
response = requests.get(url, headers=headers)
data = response.json()
play_url = data['playlist']['LD']['play_url']
print(play_url)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/468328.html
