<class 'bs4.element.ResultSet'>
content_a は、型がである値で構成される美しいスープ結果セット (つまり、型が である) です<class 'bs4.element.Tag'>
。
「content_a」を印刷すると、次のようになります。
[<div class="class1 class2">Here is the first sentence.
<br/> <br/> Here is some text "and some more text."
<br/> <br/> Here is another sentence.
<br/> Text<br/><span class="class3">Text</span></div>, <div class="class1 class2">Here is the first sentence.
<br/> <br/> Here is some text "and some more text."
<br/> <br/> Here is another sentence.
<br/> Text<br/><span class="class3">Text</span></div>, etc
だから、divの単純な反復可能なリストであるべきだと私には思えます。
に置き換えたいと思って<div class="class1 class2">
います<div class="class1 class2"><p>
(最終的な目標は、すべて<br />
を段落タグに置き換えることです)。
ソースコンテンツが私が持っている文字列である私のテストでは:
import re
blablabla = ['<div class="class1 class2">', '<div class="class1 class2">']
for _ in blablabla:
_ = re.sub('(<div class=\"class1 class2\">)', r"\1<p>",_)
print _
必要に応じて、次を返します。
<div class="class1 class2"><p>
<div class="class1 class2"><p>
content_a の各イテラブルで同じプロセスを実行しようとしています:
import re
for _ in content_a:
_ = re.sub('(<div class=\"class1 class2\">)', r"\1<p>",_)
print _
しかし、エラーが発生しています:
...in sub
return _compile(pattern, flags).sub(repl, string, count)
TypeError: expected string or buffer
したがって、2 つの例の唯一の違いは、1 つは美しいスープの結果セットであり、もう 1 つは単純なリストであるということです。
このエラーが発生する理由を誰でも見ることができますか?
編集:
誰かがここで、 sub には 3 番目の引数として文字列が必要であることを指摘しているため、私が渡す 3 番目の引数は、 type の iterable 値です<class 'bs4.element.Tag'>
。したがって、おそらくこれが問題です。しかし、後で変更するためにこれらの値の性質を保持する必要があるため、現時点ではどうすればよいかわかりません。
更新/回避策:
答えに時間を費やす人を節約するために、回避策を見つけました。基本的には、プロセスの後半でコンテンツを調整できることにread()
気付きました。文字列に必要な要素。
そして、私が思いついた小さな正規表現は次のとおりです。
string = re.sub('([^\r]*)\r', r'\1</p>\n<p>', string)