gpt4 book ai didi

python - 为什么 find_all BeautifulSoup4 函数没有返回任何内容?

转载 作者:行者123 更新时间:2023-12-01 02:34:41 24 4
gpt4 key购买 nike

刚接触 beautiful soup 4,当我在 YouTube 上搜索某些内容时,我无法使用这个简单的代码来获取标签的内容。当我打印容器时,它只是将“[]”打印为我假设的空变量。有什么想法为什么这没有捡到任何东西吗?这是否与没有在 YouTube 上捕获正确的标签有关?在搜索 HTML 中,一个结果有以下标记:

<a id="video-title" class="yt-simple-endpoint style-scope ytd-video-renderer" aria-label="Kendrick Lamar - HUMBLE. by KendrickLamarVEVO 5 months ago 3 minutes, 4 seconds 322,571,817 views" href="https://www.youtube.com/watch?v=tvTRZJ-4EyI" title="Kendrick Lamar - HUMBLE.">
Kendrick Lamar - HUMBLE.
</a>

Python 代码:

import bs4

from urllib.request import urlopen as uReq
from bs4 import BeautifulSoup as soup

search = "damn"
my_url = "https://www.youtube.com/results?search_query=" + search
uClient = uReq(my_url)
page_html = uClient.read()
uClient.close()

#html parsing
page_soup = soup(page_html, "html.parser")

containers = page_soup.find_all("a",{"id":"video-title"})
print(containers)

#result-count

最佳答案

在 YouTube 页面中动态加载结果,因此 id 和类名称将会更改。当您尝试解析页面时,请确保在 urllib 中而不是在浏览器中加载页面源时读取页面源代码查看它将解决您的问题的代码:

from bs4 import BeautifulSoup as bs
from urllib.request import *
page = urlopen('https://www.youtube.com/results?search_query=damn').read()
soup = bs(page,'html.parser')
results = soup.find_all('a',{'class':'yt-uix-sessionlink'})
for link in results:
print(l.get("href"))

代码将显示页面中的所有网址,因此您也应该解析它。

关于python - 为什么 find_all BeautifulSoup4 函数没有返回任何内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46376992/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com