如何使用 xpath 获取 youtube 标题
How to get youtube title with xpath
以下代码无法获取 youtube 标题。它以前有效。怎么了?
from lxml import etree
def get_youtube_title(youtube_id):
youtube_watch_url = 'http://www.youtube.com/watch?v='
youtube_watch_url += youtube_id
youtube = etree.HTML(urllib.request.urlopen(youtube_watch_url).read().decode('utf-8'))
#video_title = youtube.xpath("//span[@id='eow-title']/@title") # old youtube? Worked before. Not work recently.
video_title = youtube.xpath('//*[@id="container"]/h1/yt-formatted-string') # xpath copied from Inspect menu "copy | copy xpath" by right click tile in html.
return ''.join(video_title)
print(get_youtube_title('2wEA8nuThj8'))
结果为空。
yt-formatted-string
元素是JS添加的,无法从源代码中提取其文本
尝试从 meta
节点提取标题:
video_title = youtube.xpath('//meta[@name="title"]/@content')
与其让事物依赖于可能随时间变化的事物,例如 css 类 或其他可能随时间变化的 ID,不如从 <title>
中提取标题
from urllib import request
from lxml import etree
def get_youtube_title(youtube_id):
youtube_watch_url = 'https://www.youtube.com/watch?v='
youtube_watch_url += youtube_id
youtube = etree.HTML(request.urlopen(youtube_watch_url).read().decode('utf-8'))
return youtube.xpath("//title")[0].text if len(youtube.xpath("//title")) > 0 else "NO Title"
print(get_youtube_title('2wEA8nuThj8'))
以下代码无法获取 youtube 标题。它以前有效。怎么了?
from lxml import etree
def get_youtube_title(youtube_id):
youtube_watch_url = 'http://www.youtube.com/watch?v='
youtube_watch_url += youtube_id
youtube = etree.HTML(urllib.request.urlopen(youtube_watch_url).read().decode('utf-8'))
#video_title = youtube.xpath("//span[@id='eow-title']/@title") # old youtube? Worked before. Not work recently.
video_title = youtube.xpath('//*[@id="container"]/h1/yt-formatted-string') # xpath copied from Inspect menu "copy | copy xpath" by right click tile in html.
return ''.join(video_title)
print(get_youtube_title('2wEA8nuThj8'))
结果为空。
yt-formatted-string
元素是JS添加的,无法从源代码中提取其文本
尝试从 meta
节点提取标题:
video_title = youtube.xpath('//meta[@name="title"]/@content')
与其让事物依赖于可能随时间变化的事物,例如 css 类 或其他可能随时间变化的 ID,不如从 <title>
中提取标题
from urllib import request
from lxml import etree
def get_youtube_title(youtube_id):
youtube_watch_url = 'https://www.youtube.com/watch?v='
youtube_watch_url += youtube_id
youtube = etree.HTML(request.urlopen(youtube_watch_url).read().decode('utf-8'))
return youtube.xpath("//title")[0].text if len(youtube.xpath("//title")) > 0 else "NO Title"
print(get_youtube_title('2wEA8nuThj8'))