解决re.search()时出现excepted string or buffer问题

来源:互联网 发布:魔镜淘宝助手插件下载 编辑:程序博客网 时间:2024/06/06 09:56

初学python爬虫,尝试爬取百度贴吧中的内容,在获取标题时报错。

具体代码如下:

    # 获取帖子标题    def getTitle(self):        page = self.getPage(1)        pattern = re.compile('<h3 class="core_title_txt.*?>(.*?)</h3>', re.S)        result = re.search(pattern, page)        if result:            return result.group(1).strip()        else:            return None

debug之后发现是re.search中的问题,点进去看详细介绍:

def search(pattern, string, flags=0):    """Scan through string looking for a match to the pattern, returning    a match object, or None if no match was found."""    return _compile(pattern, flags).search(string)
通过字符串搜索匹配模式的匹配项,返回匹配对象,或者没有找到匹配。


而出现“except string or buffer”一般是匹配的pattern和需要在其中寻找匹配的string类型不一致,改动如下:


.read() 每次读取整个文件,它通常用于将文件内容放到一个字符串变量中,这样类型就匹配了。

正则表达式也可以改成注释中的那样,暂时没有发现有什么影响。

如果是.readlines()和findall()的组合,可以去看看这篇问答点击打开链接,可能可以帮到你。



个人见解,如有不对请多指正。



阅读全文
0 0