beautifulsoup -
使用 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)
任何意见,将不胜感激。感谢您的阅读。
解决方案
刚刚试过,它对我有用,我的 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
推荐阅读
- python - 如何将此 txt 文件转换为 pandas DataFrame?
- javascript - 导出 neo4j 图形以进行 d3 可视化
- python - 如何在使用 cv2.VideoCapture() 时降低 CPU 利用率
- spring-webflux - 在 Spring 响应式 cassandra 中进行数据转换的 Mono Slice
- java - Java 比较 10<-5 为真
- html - 导航栏重新定位的问题
- flutter - 更深入的理解:有状态的小部件总是重建,即使我在不同的观点?
- node.js - 创建外部模块时打字稿类型不匹配
- java - Spark:数据帧的复杂操作
- c# - 带有 ILogger 的单元测试基础控制器