我正在使用Wikipedia-api从给定维基百科类别的页面中提取所有文本。
如本教程中所述-
def print_categorymembers(categorymembers, level=0, max_level=2):
for c in categorymembers.values():
print("%s: %s (ns: %d)" % ("*" * (level + 1), c.title, c.ns))
if c.ns == wikipediaapi.Namespace.CATEGORY and level <= max_level:
print_categorymembers(c.categorymembers, level + 1)
cat = wiki_wiki.page("Category:Physics")
print("Category members: Category:Physics")
print_categorymembers(cat.categorymembers
但是我不能建立逻辑,怎么做,这段代码只是给了我所有的页面和一些嵌套在其他页面中的页面。 怎么做?
答案 0 :(得分:1)
如果要从页面提取文本,则必须使用text property。
因此您的代码应如下所示:
cat = wiki_wiki.page("Category:Physics")
print("Category members: Category:Physics")
for p in cat.categorymembers.values():
if p.namespace == wikipediaapi.Namespace.CATEGORY:
# it is category, so you have to make decision
# if you want to fetch also text from pages that belong
# to this category
print(p)
elif p.namespace == wikipediaapi.Namespace.MAIN:
# it is page => we can get text
print(p)
print(p.text)