python-3.x - 从维基百科获取给定类别的所有页面
问题描述
我正在使用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
但我无法构建逻辑,如何做到这一点,这段代码只是给了我所有的页面和一些嵌套到其他页面的页面。怎么做 ?
解决方案
如果要从页面中提取文本,则必须使用text 属性。
因此,您的代码可能如下所示:
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)
推荐阅读
- flutter - 为什么在变量中调用我的图像资产时出现错误?它说“FlutterError(无法加载资产:)”
- python - 服务器是否在主机 localhost 上运行并接受端口 5432 上的 TCP/IP 连接?
- javascript - 如何在反应应用程序中添加外部javascript
- bazel - Bazel - 取决于生成的输出
- javascript - 设置动态创建的表格的列宽以适合内容
- c# - 我可以从 ASP.NET MVC 中的 Model.edmx 文件中获取存储过程脚本吗?
- agda - 目标隐含的参数定理
- javascript - 编辑表格中的单元格时如何更改字体大小
- api - 如何限制对anypoint平台公共url的访问
- php - Laravel - 查询以多对多关系连接表