2016-05-31 151 views
1

所以我想网络刮https://en.wikipedia.org/wiki/FIFA_World_Rankings和刮在页面上的第一个表,但它没有奏效,我得到一个错误'NoneType'对象可调用。在Python中的网页刮

这里是我的代码:

from bs4 import BeautifulSoup 
import urllib2 

soup = BeautifulSoup(urllib2.urlopen("https://en.wikipedia.org/wiki/FIFA_World_Rankings").read()) 

for row in soup('table', {'class': 'wikitable'})[0].tbody('tr'): 
    tds = row('td') 
    print tds[0].string, tds[1].string 

我不知道很多关于HTML,我所知甚少网页抓取。

+2

'row('td')'...'row'不是一种方法,所以它不是“可调用的”。 'tbody('tr')'也许相同 –

+0

另外 - 我建议你使用请求库,而不是'urllib2'库 - 'request'是一种更好的获取网页的方式。 –

回答

2

您错过了findAll(或find_all,如果您想要Pythonic)功能来搜索元素下的所有标签。

您可能还想对数据进行检查以确保您没有像这样得到IndexError。

for row in soup('table', {'class': 'wikitable'})[0].findAll('tr'): 
    tds = row.findAll('td') 
    if len(tds) > 1: 
     print tds[0].text, tds[1].text 

下面是它给

Argentina 1532 
 Belgium 1352 
 Chile 1348 
 Colombia 1337 
 Germany 1309 
 Spain 1277 
 Brazil 1261 
+0

'.string'不起作用。 '.text'起作用。 –

+0

在python2中自己运行。 'beautifulsoup4(4.4.1)' –

+0

那么这可能是一个平台问题。给我“没有”。 –

1
import requests 
from bs4 import BeautifulSoup 

request = requests.get("https://en.wikipedia.org/wiki/FIFA_World_Rankings") 
sourceCode = BeautifulSoup(request.content) 
tables = sourceCode.select('table.wikitable') 
table = tables[0] 

print table.get_text() 

还输出,如果你想要的结果的列表:

list = [text for text in table.stripped_strings] 
+0

这给了我一个错误,说:找不到具有您请求的功能的树生成器:html5lib。你需要安装一个解析器库吗? –

+0

您可以用'html_parser'替换'html5lib',或者将其删除。 –

+0

它没有它的工作原理,我只是默认html5lib,因为有些网站是挑剔的,对不起,应该已经指定了依赖关系 – Matt

0

这应该工作。您需要使用find_all来查找标签。另外,在Wiki文章中,团队等级出现在表格第3-22行,因此是if条件。

from bs4 import BeautifulSoup 
import urllib2 

soup = BeautifulSoup(urllib2.urlopen("https://en.wikipedia.org/wiki/FIFA_World_Rankings").read()) 

for i,row in enumerate(soup('table', {'class': 'wikitable'})[0].find_all('tr')): 
    if i > 2 and i < 23: 
     data = row.find_all('td') 
     print i,data[0].text, data[1].text 
+0

这给了正确的输出。如果你不介意解释枚举部分,这将是奇妙 –

+0

@AdamWarner ['enumerate()'](https://docs.python.org/3/library/functions.html#enumerate) –

+1

请参阅'for row例如在行中给出每行。 '对于我,在枚举(row)行中'给出'i'中的当前索引和''行中的行。我希望我说清楚。 –