Py学习  »  Python

如何使用用于python的Wikipedia API获取图像标题

wos • 4 年前 • 814 次点击  

假设我在页面上有图片的网址,

 for i in wiki.images:
    print (i)

有没有简单的方法获得图片标题?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/51220
 
814 次点击  
文章 [ 2 ]  |  最新文章 4 年前
David
Reply   •   1 楼
David    4 年前

如果您要获取的是图像标记的title属性(即,来自HTML),则可以执行类似于以下操作:

import wikipedia
from html.parser import HTMLParser

class WikipediaImageParser(HTMLParser):
    def handle_starttag(self, tag, attrs):
        if tag == 'img':
            try:
                print(dict(attrs)['title'])
            except KeyError as e:
                return # do nothing

page = wikipedia.page("History_of_Japan")
parser = WikipediaImageParser()
parser.feed(page.html())

您可以解析HTML来获取每个图像的属性,然后检查是否有title属性。

Chetan Vashisth
Reply   •   2 楼
Chetan Vashisth    4 年前

尝试:

如果您正在遍历所有图像的url,则可以尝试

for i in wiki.images:
    i.split('/')[-1]  # -1 because the name is at the last part of the url

所以上面的代码会给你图像名。

希望这有帮助。。。