2016-04-16 20 views
2

htmlファイル内で一致させようとしています。これはhtmlです:Pythonの正規表現がhtmlファイルで一致する

<td> 
<b>BBcode</b><br /> 
<textarea onclick='this.select();' style='width:300px;  height:200px;' /> 
[URL=http://someimage.com/LwraZS1]   [IMG]http://t1.someimage.com/LwraZS1.jpg[/IMG][ [/URL] [URL=http://someimage.com/CDnuiST] [IMG]http://t1.someimage.com/CDnuiST.jpg[/IMG] [/URL] [URL=http://someimage.com/Y0oZKPb][IMG]http://t1.someimage.com/Y0oZKPb.jpg[/IMG][/URL] [URL=http://someimage.com/W2RMAOR][IMG]http://t1.someimage.com/W2RMAOR.jpg[/IMG][/URL] [URL=http://someimage.com/5e5AYUz][IMG]http://t1.someimage.com/5e5AYUz.jpg[/IMG][/URL] [URL=http://someimage.com/EWDQErN][IMG]http://t1.someimage.com/EWDQErN.jpg[/IMG][/URL] 
</textarea> 
</td> 

[to]からすべてのBBコードを抽出します。

そして、これは私のコードです:

import re 
x = open('/xxx/xxx/file.html', 'r').read 
y = re.compile(r"""<td> <b>BBcode</b><br /><textarea onclick='this.select();' style='width:300px; height:200px;' />. (. *) </textarea> </td>""") 
z = y.search(str(x()) 
print z   

しかし、私はこれを実行したときに、私は間違いありなしオブジェクトを取得...?

+0

は '')(読み括弧忘れました。 –

+0

何もない、まだ何も取得..正規表現が間違っているかもしれません.. –

+0

ええと、answer.checkを投稿しました。 –

答えて

0

私はこのためにパーサを使用します。

from html import HTMLParser 

class MyHtmlParser(HTMLParser): 
    def __init__(self): 
     self.reset() 
     self.convert_charrefs = True 
     self.dat = [] 
    def handle_data(self, d): 
     self.dat.append(d.strip()) 
    def return_data(self): 
     return self.dat 
>>> with open('sample.html') as htmltext: 
     htmldata = htmltext.read() 
>>> parser = MyHtmlParser() 
>>> parser.feed(htmldata) 
>>> res = parser.return_data() 
>>> res = [item for item in filter(None, res)] 
>>> res[0] 
'BBcode' 
>>> 
+0

あなたの答えをありがとう!実際にこのスクリプトを実行してres [0]を印刷しようとすると、html:box-shadow { -moz-box-shadow:3px 3px 5px#000000; -webkit-box-shadow:3px 3px 5px#000000; ボックスシャドウ:3px 3px 5px#000000; } –

+0

ああ、私は第4引数を印刷しなければなりませんでした。まさに私が必要なもの。どうもありがとう!最後に、出力をファイルに書き込む方法は? –

+0

単純なテキストファイルとして: 'open( 'filename.txt'、 'w')をnewfile:newfile.write(res [0])' –

0

私はregexオブジェクトを引き出すために、z.group()のようなものを追加する必要があると思いますよね?だから、それを行う可能性があります)(

印刷z.groupに

をあなたの最後の行を変更します。

0
import re 
x = open('/xxx/xxx/file.html', 'rt').read() 
r1 = r'<textarea.*?>(.*?)</textarea>' 
s1 = re.findall(r1, s, re.DOTALL)[1] # just by inspection 
r2 = r'\[(.*?)\]' 
s2 = re.findall(r2, s1) 
for u in s2: 
    print(u) 
+0

ありがとう、それは動作しますが、それはhtmlの別の部分を取得するので、すべての内部