ValueError:索引79处不支持格式字符“a”(0x61)

2024-04-27 05:11:18 发布

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

我正试图从一个使用漂亮的soup4和python的网站上获取数据。这是我的密码

from bs4 import BeautifulSoup
import urllib2
i = 0
for i in xrange(0,38):
    page=urllib2.urlopen("http://www.sfap.org/klsfaprep_search?page={}&type=1&strname=&loc=&op=Lancer%20la%20recherche&form_build_id=form-72a297de309517ed5a2c28af7ed15208&form_id=klsfaprep_search_form" %i) 
    soup = BeautifulSoup(page.read())
    for eachuniversity in soup.findAll('div',{'class':'field-item odd'}):
        print ''.join(eachuniversity.findAll(text=True)).encode('utf-8')
    print ',\n'
i= i+ 1

我认为问题出在我给出的URL和increment语句中。我能一页一页地读。但只有当我给出xrange的时候。在


Tags: inimportformidforsearchpageurllib2
1条回答
网友
1楼 · 发布于 2024-04-27 05:11:18

ValueError的原因

您正在混合{}格式和%格式。在

>>> '{}%20la' % 1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: unsupported format character 'a' (0x61) at index 6
>>> '{}%20la'.format(1)
'1%20la'

我建议您使用{}格式,因为在URL中,有多个%

^{pr2}$

完整代码

你不需要i = 0i = i + 1,因为for i in xrange(0,38)会照顾好它。在

import urllib2 # Import standard library module first. (PEP-8)

from bs4 import BeautifulSoup

for i in xrange(0,38):
    page = urllib2.urlopen("http://www.sfap.org/klsfaprep_search?page={}&type=1&strname=&loc=&op=Lancer%20la%20recherche&form_build_id=form-72a297de309517ed5a2c28af7ed15208&form_id=klsfaprep_search_form" .format(i))
    soup = BeautifulSoup(page.read())
    for eachuniversity in soup.findAll('div',{'class':'field-item odd'}):
        print ''.join(eachuniversity.findAll(text=True)).encode('utf-8')
    print ',\n'

相关问题 更多 >