正则表达式 - python re.sub替换不成功
本文介绍了正则表达式 - python re.sub替换不成功的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
我在学习爬虫的时候想把里面的标签去掉,但是使用re.sub不成功。代码如下:
#!usr/bin/env python3
#coding:utf-8
from urllib.request import urlopen
from bs4 import BeautifulSoup
import re
html = urlopen("http://www.jianshu.com")
bsObj = BeautifulSoup(html,"lxml")
txt = bsObj.findAll("p",{"class":re.compile("abstract")})
for word in txt:
if '<p class="abstract">' in word:
newword = re.sub(r'<p class="abstract">','\n',word)
print(newword)
else:
print(word)
请问这是是什么问题,谢谢!
解决方案
In [19]: type(word)
Out[19]: bs4.element.Tag
找到原因了,word不是一个字符串。
这篇关于正则表达式 - python re.sub替换不成功的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文