首页 > 解决方案 >
使用 bs4 用换行符替换标签的问题

问题描述

问题:我无法<br>使用 Beautiful Soup 4 将标签替换为换行符。

代码:我的程序(它的相关部分)目前看起来像

for br in board.select('br'):
    br.replace_with('\n')

但我也尝试board.find_all()过代替board.select().

结果:当我使用时,board.replace_with('\n')所有<br>标签都替换为字符串字面量\n。例如,<p>Hello<br>world</p>最终会变成Hello\nworld. 使用board.replace_with(\n)导致错误

File "<ipython-input-27-cdfade950fdf>", line 10
    br.replace_with(\n)
                       ^
SyntaxError: unexpected character after line continuation character

其他信息:我正在使用 Jupyter Notebook,如果有任何相关性的话。这是我的完整程序,因为其他地方可能存在一些我忽略的问题。

import requests
from bs4 import BeautifulSoup
import pandas as pd

page = requests.get("https://boards.4chan.org/g/")
soup = BeautifulSoup(page.content, 'html.parser')
board = soup.find('div', class_='board')

for br in board.select('br'):
    br.replace_with('\n')

message = [obj.get_text() for obj in board.select('.opContainer .postMessage')]
image = [obj['href'] for obj in board.select('.opContainer .fileThumb')]
pid = [obj.get_text() for obj in board.select('.opContainer .postInfo .postNum a[title="Reply to this post"]')]
time = [obj.get_text() for obj in board.select('.opContainer .postInfo .dateTime')]

for x in range(len(image)):
    image[x] = "https:" + image[x]

post = pd.DataFrame({
    "ID": pid,
    "Time": time,
    "Image": image,
    "Message": message,
    })
post

pd.options.display.max_rows
pd.set_option('display.max_colwidth', -1)

display(post)

任何意见,将不胜感激。感谢您的阅读。

标签: beautifulsoup

解决方案


刚刚试过,它对我有用,我的 bs4 版本是 4.8.0,我使用的是 Python 3.5.3,例如:

from bs4 import BeautifulSoup

soup = BeautifulSoup('hello<br>world')

for br in soup('br'):
    br.replace_with('\n')

# <br> was replaced with \n successfully
assert str(soup) == '<html><body><p>hello\nworld</p></body></html>'

# get_text() also works as expected
assert soup.get_text() == 'hello\nworld' 

# it is a \n not a \\n 
assert soup.get_text() != 'hello\\nworld'

我不习惯使用 Jupyter Notebook,但似乎您的问题是,无论您使用什么来可视化数据,都在向您显示字符串表示形式,而不是实际打印字符串,希望这会有所帮助,问候,adb


推荐阅读