使用Python BeautifulSoup提取论坛评论文本时仅能获取首行问题求助
问题原因
你当前的代码仅提取了<blockquote>标签的第一个子节点内容,所以只会返回<br>标签之前的第一行文本。
解决方法
直接调用BeautifulSoup元素内置的get_text()方法即可,该方法会自动提取标签内所有文本节点的内容,自动忽略HTML标签。
修改后的代码
r = requests.get("https://example.com/threads/73956/page2", headers=headers, cookies=cookies) soup = BeautifulSoup(r.content, "html.parser") comments = soup.find_all('div',{'class':'wwCommentBody'}) for div in comments: text_block = div.find('blockquote',{'class':'postcontent restore'}) if text_block: # 提取全部文本,strip=True自动去除各文本片段前后的空白 full_comment = text_block.get_text(strip=True) print(full_comment)
可选配置
如果需要保留评论原本的换行结构,可以增加separator参数,将不同行的内容用换行符分隔:
full_comment = text_block.get_text(separator='\n', strip=True)
内容的提问来源于stack exchange,提问作者Marvel
相关产品推荐
相关产品推荐

