I use BeautifulSoup for web-scraping by python.
Issue is "All <br> tags removed when getText()".
I know getText() function is extract only texts.
But in result, All text became into 1-line, Can't see same as web-site.
What I want : "When I use getText(), I want only <br> tag is NOT remove. Just only replace to line-break(\n)"
If you have idea, Please help me.
Sample text ↓
# - This is text of before getText() -------
<dd class="resbody">
<a class="auto" href="/a/Linux">Linux</a>勉強するならCは当然として<br/><a class="auto" href="/a/Python">Python</a>も押さえておかないと<br/>大変になるかなあと感じている。
</dd>
# - This is text of after getText() -------
Linux勉強するならCは当然としてPythonも押さえておかないと大変になるかなあと感じている
# - This is "What I want" after getText() -----
Linux勉強するならCは当然として
Pythonも押さえておかないと
大変になるかなあと感じている。
My code is this ↓
soup = BeautifulSoup(r.content, "html.parser")
resheads = soup.find_all("dt", class_="reshead")
resbodys = soup.find_all("dd", class_="resbody")
formattedHead = []
formattedBody = []
resCount = 0
# 整形済みレスヘッダ部取得
for rhead in resheads:
h = rhead
h = h.getText() # テキスト部分抽出
h = h.replace('\n', '') # 不要な改行を削除
h = h.replace(' ', '') # 不要な空白を削除
h = h.replace(')', ') ') # 整形
h = h.replace('ID:', ' ID:') # 整形
formattedHead.append(h)
# 整形済みレス本体部取得
for rbody in resbodys:
b = rbody
b = b.getText() # <-- <br> is removed at here.
b = b.strip() # 前後から空白削除
b = b.strip('\n') # 前後から改行削除
formattedBody.append(b)
# カウントするのはheadでもbodyでもどちらでもいいのだが、この数が本ページにおけるレス数になる(通常は30だが最終ページでは少ない可能性あり)
resCount += 1
FYI(Entire code) : https://github.com/we-yu/sb.webscraping/blob/other/QuestionSrc/nicopedy_saver.py
Aucun commentaire:
Enregistrer un commentaire