【问题标题】:Why there is no output showing in this YouTube crawler in python?为什么这个 YouTube 爬虫在 python 中没有显示输出?
【发布时间】:2017-09-03 09:35:14
【问题描述】:
import requests 
from bs4 import BeautifulSoup 

youtube = "https://www.youtube.com/results?search_query=" 

def get_address(keyword): 
    query = youtube + keyword 
    source_code = requests.get(query) 
    plain_text = source_code.text 
    soup = BeautifulSoup(plain_text, "html.parser") 

    for link in soup.findAll('a', {'id': 'video-title'}): 
        href = link.get('href') 
        print(href)
        break

get_address("scishow")

程序运行成功,但没有显示视频的地址,输出中什么也没有显示。

【问题讨论】:

  • 您的代码很好,它没有在输出中显示任何内容的唯一原因是您要查找的 a 标记不存在。 <a id="video-title" ...> 稍后会使用 JavaScript 添加到页面中,当您检索初始 HTML 代码时,它当然还没有执行。
  • 很可能是因为页面使用了JS。在这种情况下请求将无用,请改用selenium

标签: python beautifulsoup web-crawler


【解决方案1】:

Youtube 大量运行在 javascript 上。我建议你使用硒。这是您的更新代码:

from selenium import webdriver
from bs4 import BeautifulSoup

youtube = "https://www.youtube.com/results?search_query="

def get_address(keyword):
    query = youtube + keyword
    browser = webdriver.Chrome()
    browser.get(query)
    plain_text = browser.page_source
    browser.quit()
    soup = BeautifulSoup(plain_text, "html.parser")

    for link in soup.findAll('a', {'id': 'video-title'}):
       href = link.get('href')
       print(href)

get_address("scishow")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-26
    • 1970-01-01
    • 1970-01-01
    • 2021-04-04
    • 1970-01-01
    • 1970-01-01
    • 2018-05-31
    • 1970-01-01
    相关资源
    最近更新 更多