【发布时间】:2019-09-02 17:36:45
【问题描述】:
我需要从 youtube 播放列表中提取 youtube 链接及其名称。
所以我只是尝试使用SelectorGadget(Chrome Extension) 来提取 CSS 标记,但是当我试图获取关于 BeautifulSoup 返回none 之类的任何信息时,我不知道我哪里出错了。
下面是我写的代码:
from os import sys
import requests
from bs4 import BeautifulSoup
import re
try:
# checking url format
url_pattern = re.compile("^(?:http|https|ftp):\/\/[a-zA-Z0-9_~:\-\/?#[\]@!$&'()*+,;=`^.%]+\.[a-zA-Z0-9_~:\-\/?#[\]@!$&'()*+,;=`^.%]+$")
# playlist_url = input("Enter your youtbe playlist url: ")
# getting input directly from user commandline
playlist_url = sys.argv[1]
if not bool(url_pattern.match(playlist_url)) :
raise ValueError("Enter valid link")
get_links_from_youtube_playlist(playlist_url)
except ValueError as value_error:
print(value_error)
然后我会将 URL 传递给另一个函数:
def get_links_from_youtube_playlist(youtube_playlist_url):
request_response = requests.get(youtube_playlist_url)
# using "html.parser" lib
# soup_object = BeautifulSoup(request_response.text, 'html.parser')
# using "lxml" - Processing XML and HTML with Python
soup_object = BeautifulSoup(request_response.text, 'lxml')
# not working?!
url_list = soup_object.select("#video-title")
print(url_list)
# this is not working too?!
div_content = soup_object.find("div", attrs={"class" : "content"})
print(div_content)
另外,我通过以下命令运行它:
python3 test.py https://www.youtube.com/playlist\?list\=PLZHQObOWTQDPD3MizzM2xVFitgF8hE_ab
在select 或 fenter code hereind 方法之后打印 BeautifulSoup 对象时,我的输出为 None。因为 id 存在于页面中,它不应该找到任何有意义的东西吗?
选择器小工具仅在单击该部分时才显示#video-title,即使我无法访问div 我应该如何提取链接和链接名称?
【问题讨论】:
-
该页面中没有
id="video-title"。有很多class="video-title"。听起来这个ID是你点击扩展时添加的东西,但是BS怎么知道你想要哪个项目? -
使用
.video-title按类选择。 -
@Barmar 谢谢,谢谢,但我已经尝试过
url_list = soup_object.select(".video-title")它仍然什么都不返回 ([ ]) ` -
requests.get()返回的页面和浏览器得到的不一样。 YouTube 显然正在检查用户代理。请参阅stackoverflow.com/questions/10606133/… 了解如何自定义用户代理。
标签: python python-3.x web-scraping beautifulsoup