维基百科页面上的图像标题

时间:2018-01-02 19:34:56

标签: python text nlp wikipedia

我想查看维基百科文章中的标题(每张图片下方的文字)。我希望解析这些字符串(主要使用正则表达式)然后如果匹配,我想保存该图像的链接。

我一直在直接导入维基百科以解析文本,但在浏览网络后,我发现我需要一种不同类型的解析器。我尝试使用mwparserfromhell和pywikibot,但我无法为我解决pywikibot错误,只是mwparserfromhell给了我空的结果。

在不使用DBPpedia的情况下执行上述任何帮助?

1 个答案:

答案 0 :(得分:0)

这是我写的要做的

#!/usr/bin/python3

"""
    parse.py

    MediaWiki API Demos
    Demo of `Parse` module: Parse content of a page

    MIT License
"""

import requests
from pprint import pprint

S = requests.Session()

URL = "https://en.wikipedia.org/w/api.php"

page_title= "Photosynthesis"
PARAMS = {
    "action": "parse",
    "page": page_title,
    "format": "json"
}

R = S.get(url=URL, params=PARAMS)
DATA = R.json()
page = (DATA["parse"]["text"]["*"])
from bs4 import BeautifulSoup
soup = BeautifulSoup(page, 'html.parser')
thumb_divs = soup.findAll("div", {"class": "thumbinner"})

images = []
for div in thumb_divs:
    image = div.findAll("img")[0]['src']
    caption = div.findAll("div")[0].text

    image_and_caption = {
        'image_url' : image,
        'image_caption' : caption
    }
    images.append(image_and_caption)

return_value = {'term' : page_title, 'images' : images }

pprint(return_value)
相关问题