我正在尝试使用漂亮的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和增量语句中。我能够逐页搜索。但只有当我给出xrange时。
答案 0 :(得分:3)
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'
我建议您使用{}
格式,因为在网址中,有多个%
。
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))
您不需要i = 0
和i = 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'