正则表达式 - python re.sub替换不成功
黄舟
黄舟 2017-04-18 10:12:11
0
2
484

我在学习爬虫的时候想把里面的标签去掉,但是使用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)

请问这是是什么问题,谢谢!

黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

Antworte allen(2)
黄舟
In [19]: type(word)
Out[19]: bs4.element.Tag

找到原因了,word不是一个字符串。

黄舟

字符串对象p并不包含"sub"方法:

newword = p.sub('\n', word) # -> re.sub(.....)

写一小段代码给题主参考一下子:

import re
word = '<p class="abstract">AAAA<p class="abstract">bbb'
p = '<p class="abstract">'
newword = re.sub(p, '\n', word)

'''
Result:
In [21]: newword
Out[21]: '\nAAAA\nbbb'

In [22]: print newword

AAAA
bbb

In [23]:
'''
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!