这是一个带有网页爬虫的代码。 我是个初学者Python。所以呢我不知道怎么解决。 搜索似乎有问题()
# -*- coding:utf-8 -*-
import urllib,urllib2,re
class BDTB:
def __init__(self,baseUrl,seeLZ):
self.baseUrl = baseUrl
self.seeLZ = '?see_lz' + str(seeLZ)
def getPage(self,pageNum):
try:
url = self.baseUrl + self.seeLZ + '&pn=' + str(pageNum)
request = urllib2.Request(url)
response = urllib2.urlopen(request)
#print response.read().decode('utf-8')
return response
except urllib2.URLError,e:
if hasattr(e,'reason'):
print u'连接百度贴吧失败,错误原因',e.reason
return None
def getTitle(self):
page = self.getPage(1)
pattern = re.compile('<h3 class.*?px">(.*?)</h3>',re.S)
result = re.search(pattern,page)
if result:
print result.group(1)
return result.group(1).strip()
else:
return None
baseURL = 'http://tieba.baidu.com/p/4095047339'
bdtb = BDTB(baseURL,1)
bdtb.getTitle()
这将引发
TypeError: expected string or buffer
,因为您正在将从urllib2.urlopen(request)
返回的对象传递到re.search()
,而它需要str
。你知道吗如果将返回值更改为:
返回请求中包含的文本:
脚本正常工作,执行后返回:
另外,由于您使用的是
Python 2.x
,您可能需要将对象从class BDTB:
更改为class BDTB(object)
,以便使用new style classes。你知道吗相关问题 更多 >
编程相关推荐