我的 python 网络抓取工具中的 KeyError 和 TypeError

KeyError and TypeError in my python web scraper

很抱歉这个含糊不清的标题。但是对于我来说,用一句话来概括我的问题,真的没有更好的方法了。

我试图从一个法语网站获取学生和成绩信息。 link 是这个 (http://www.bankexam.fr/resultat/2014/BACCALAUREAT/AMIENS?filiere=BACS)

我的代码如下:

import time
import urllib2
from bs4 import BeautifulSoup
regions = {'R\xc3\xa9sultats Bac Amiens 2014':'/resultat/2014/BACCALAUREAT/AMIENS'}
base_url = 'http://www.bankexam.fr'
tests = {'es':'?filiere=BACES','s':'?filiere=BACS','l':'?filiere=BACL'}
for i in regions:
    for x in tests:
        # create the output file
        output_file = open('/Users/student project/'+ i + '_' + x + '.txt','a')
        time.sleep(2) #compassionate scraping
        section_url = base_url + regions[i] + tests[x]  #now goes to the x test page of region i 
        request = urllib2.Request(section_url)
        response = urllib2.urlopen(request)
        soup = BeautifulSoup(response,'html.parser')
        content = soup.find('div',id='zone_res')
        for row in content.find_all('tr'):
            if row.td:
                student = row.find_all('td')
                name = student[0].strong.string.encode('utf8').strip()
                try:
                    school = student[1].strong.string.encode('utf8')
                except AttributeError:
                    school = 'NA'
                result = student[2].span.string.encode('utf8')
                output_file.write ('%s|%s|%s\n' % (name,school,result))
        # Find the maximum pages to go through
        if soup.find('div','pagination'): 
            import re
            page_info = soup.find('div','pagination')
            pages = []
            for i in page_info.find_all('a',re.compile('elt')):
                try:
                    pages.append(int(i.string.encode('utf8')))
                except ValueError:
                    continue
            max_page = max(pages)
            # Now goes through page 2 to max page
            for i in range(1,max_page):
                page_url = '&p='+str(i)+'#anchor'
                section2_url = section_url+page_url
                request = urllib2.Request(section2_url)
                response = urllib2.urlopen(request)
                soup = BeautifulSoup(response,'html.parser')
                content = soup.find('div',id='zone_res')
                for row in content.find_all('tr'):
                    if row.td:
                        student = row.find_all('td')
                        name = student[0].strong.string.encode('utf8').strip()
                        try:
                            school = student[1].strong.string.encode('utf8')
                        except AttributeError:
                            school = 'NA'
                        result = student[2].span.string.encode('utf8')
                        output_file.write ('%s|%s|%s\n' % (name,school,result))

关于代码的更多说明: 我创建了 'regions' 字典和 'tests' 字典,因为我还需要收集 30 个其他区域,这里只包含一个用于展示。我只对三个测试(ES、S、L)的测试结果感兴趣,所以我创建了这个 'tests' 字典。

不断出现两个错误, 一个是

KeyError: 2

错误被 linked 到第 12 行,

section_url = base_url + regions[i] + tests[x]

另一个是

TypeError: cannot concatenate 'str' and 'int' objects

这是 link第 10 行。

我知道这里有很多信息,我可能没有列出最重要的信息来帮助我。但是让我知道我该怎么做才能解决这个问题! 谢谢

问题是您在多个地方使用了变量 i

在文件顶部附近,您执行:

for i in regions:

因此,在某些地方 i 被期望成为 regions 字典的关键字。

以后再用的时候麻烦就来了。您在两个地方这样做:

for i in page_info.find_all('a',re.compile('elt')):

并且:

for i in range(1,max_page):

第二个是导致异常的原因,因为分配给 i 的整数值没有出现在 regions 字典中(也不能将整数添加到字符串).

我建议重命名其中的部分或全部变量。如果可能的话,给它们起有意义的名字(i 对于 "index" 变量来说可能是可以接受的,但我会避免将它用于其他任何事情,除非你正在打高尔夫球)。