如何使用pythonwikipedia库从wikipedia提取infobox vcard

2024-09-25 10:18:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在尝试使用wikipediapython包提取infobox内容。在

我的代码如下(对于this page):

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

当我进入时:

^{pr2}$

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

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

这是我和Beautiulsoup合作的结果:

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

我也查看了Wikidata,但是它没有包含我需要的表中的大部分信息。在

我不一定把python包作为解决方案。 任何能够解析表的东西都会很棒。在

最好,我想要一个包含infobox值的字典:

Type     Private
Industry Retail

等等。。。在


Tags: 代码import信息内容hdrpagesiteurllib2
2条回答

我的解决方案

from bs4 import BeautifulSoup as bs
query = 'albert einstien'
url = 'https://en.wikipedia.org/wiki/'+query
def infobox() :
raw = urllib.urlopen(url)
soup = bs(raw)
table = soup.find('table',{'class':'infobox vcard'})
for tr in table.find_all('tr') :
    print tr.text

基于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上测试,但未在其他wiki页面上完全测试。在

相关问题 更多 >