python - 如何使用 python 维基百科库从维基百科中提取信息框 vcard

标签 python beautifulsoup wikipedia-api

我一直在尝试使用维基百科 python 包提取信息框内容。

我的代码如下(this page):

import wikipedia
Aldi = wikipedia.page('Aldi')

当我输入时:

Aldi.content

我得到文章文本但没有信息框。

我曾尝试从 DBPedia 获取数据,但没有成功。我也尝试过使用 BeautifulSoup4 提取页面,但该表的结构很奇怪(因为有一个图像跨越两列,后面跟着未命名的列。

这是我对 BeautifulSoup 的最大了解:

from bs4 import BeautifulSoup
import urllib2
site= "http://en.wikipedia.org/wiki/Aldi"
hdr = {'User-Agent': 'Mozilla/5.0'}
req = urllib2.Request(site,headers=hdr)
page = urllib2.urlopen(req)
soup = BeautifulSoup(page)
print soup

我也查看了维基数据,但它不包含我需要从表格中获取的大部分信息。

我不一定将 python 包作为解决方案。 任何可以解析该表的东西都会很棒。

最好,我想要一个包含信息框值的字典:

Type     Private
Industry Retail

等...

最佳答案

基于BeautifulSoup的解决方案:

from bs4 import BeautifulSoup
import urllib2
site= "http://en.wikipedia.org/wiki/Aldi"
hdr = {'User-Agent': 'Mozilla/5.0'}
req = urllib2.Request(site,headers=hdr)
page = urllib2.urlopen(req)
soup = BeautifulSoup(page.read())
table = soup.find('table', class_='infobox vcard')
result = {}
exceptional_row_count = 0
for tr in table.find_all('tr'):
    if tr.find('th'):
        result[tr.find('th').text] = tr.find('td').text
    else:
        # the first row Logos fall here
        exceptional_row_count += 1
if exceptional_row_count > 1:
    print 'WARNING ExceptionalRow>1: ', table
print result

测试于 http://en.wikipedia.org/wiki/Aldi ,但未在其他维基页面上进行全面测试。

关于python - 如何使用 python 维基百科库从维基百科中提取信息框 vcard,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26476446/

相关文章:

python - 共享层,不同模型

python - MongoDB:创建嵌入文档

python-3.x - Python http.client.Incomplete Read(0 bytes read) 错误

python - 通过bs4获取html表数据到python中

python - BeautifulSoup 获取列表的 href - 需要简化脚本 - 替换多处理

wikipedia - 如何知道来自 API 的维基百科内容是否包含有用的文章或不明确的文章

javascript - 为什么我的 wikipedia opensearch ajax 请求不能成功返回?

python - 直接在.htaccess中AddHandler

python - Tensorflow中按字符串选择不同的模式

python - 到达 JSON 中未知值后面的字符串