Skip to main content
 首页 » 编程设计

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

2024年10月25日10qq78292959

我一直在尝试使用维基百科 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 ,但未在其他维基页面上进行全面测试。