我试图阅读网页并将格式化文本输出到文本文件。下面的代码使用格式打印到shell,但是当我将它写入文件时,它将它放在一行(文本中有换行符/ n)。
我尝试过各种各样的东西,比如不把它转换成字符串,使用漂亮的汤美化,但似乎没有产生带格式的文本文件。我假设我遗漏了一些相当基本的东西。任何帮助或指导都将非常感激。
# Import
from urllib.request import urlopen
from bs4 import BeautifulSoup
#The actual code
URL = "https://simple.wikipedia.org/wiki/castle" #The target URL
html = urlopen(URL).read() # Reads the url to variable html
soup = BeautifulSoup(html, "lxml") # Uses BS4 to create the soup using the lxml parser
soup = soup.get_text() # Extracts the text
print(soup) # Prints to python 3.5.1 shell, formatted as I would expect
# Now writing what I have extracted to a text file
file = open("TextOutput.txt", 'w') # Creates the file and opens as write (w)
file.writelines(str(soup.encode('UTF-8'))) # Tried file.write/lines(soup), convertion to string and encoding as UTF-8 needed to avoid errors
file.close()
文件输出的示例如下:
b' \ n \ n \ nCastle - 简体英语维基百科,免费的百科全书\ ndocument.documentElement.className = document.documentElement.className.replace(/(^ | \ s)client-nojs(\ s | $)/," $ 1client-js $ 2"); \ n(window.RLQ = window.RLQ || [])。push(function(){mw.config.set({&# 34; wgCanonicalNamespace":""" wgCanonicalSpecialPageName":假," wgNamespaceNumber":0," wgPageName":&#34 ;城堡"" wgTitle":"城堡"" wgCurRevisionId":5333370," wgRevisionId":5333370," wgArticleId":15933" wgIsArticle":真," wgIsRedirect":假," wgAction":"视图"&#34 ; wgUserName":空," wgUserGroups":[" &#34]," wgCategories":["城堡"] " wgBreakFrames":假," wgPageContentLanguage":"恩"" wgPageContentModel":" wikitext的"&# 34; wgSeparatorTransformTable":["""&#34]," wgDigitTransformTable":[""" &#34]," wgDefaul tDateFormat":" DMY"" wgMonthNames":[""" 1""二月" "三月"" 4月""五月"" 6月"" 7月""八月"" 9月"" 10月""十一月""十二月"]" wgMonthNamesShort" :"""扬""二月""三月""四月"&#34 ;可""君""七月""八月""九月""十月" "十一月""减速&#34]," wgRelevantPageName":"城堡"" wgRelevantArticleId":15933,& #34; wgRequestId":" VxUR5gpAIDAAAEXY6FMAAACC"" wgIsProbablyEditable":真," wgRestrictionEdit":[]," wgRestrictionMove":[ ]" wgWikiEditorEnabledModules" {"工具栏":真,"对话框":真,"预览":假,"发布& #34;:假}" wgBetaFeaturesFeatures":[]," wgMediaViewerOnClick":真," wgMediaViewerEnabledByDefault":真," wgVisualEditor&#34 ;: {" pageLanguageCode":"恩"" pageLanguageDir":" LTR"" usePageImages":真," usePageDescriptions&#34 ;:真}" wgPreferredVariant":"恩"" wgRelatedArticles":空," wgRelatedArticlesUseCirrusSearch":真," wgRelatedArticlesOnlyUseCirrusSearch& #34;:假," wgULSAcceptLanguageList":[]," wgULSCurrentAutonym":"英语"" wgCategoryTreePageCategoryOptions":" { \"模式\":0,\" hideprefix \":20,\" showcount \":真,\"命名空间\& #34;:假}"" wgNoticeProject":"维基"" wgCentralNoticeCategoriesUsingLegacy":["筹款"&# 34;筹款&#34]," wgCentralAuthMobileDomain":假," wgWikibaseItemId":" Q23413"" wgVisualEditorToolbarScrollOffset":0}); mw.loader.implement(" user.options",功能($,jQuery的){mw.user.options.set({"变体":"恩" });}); mw.loader.implement(" user.tokens",功能($,jQuery){\ nmw.user.tokens.set({" editToken":" + \\"," patrolToken":" + \\"" watchToken":&#34 + \\"" csrfToken":&#34 + \\"} ); / @nomin * /; \ n \ n}); mw.loader.load([" mw.MediaWikiPlayer.loader"" mw.PopUpMediaTransform&#34 ;, " mw.TMHGalleryHook.js"" mediawiki.page.startup"" mediawiki.legacy.wikibits"" ext.centralauth.centralautologin&#34 ;," mmv.head"" ext.visualEditor.desktopArticleTarget.init"" ext.uls.init""&ext.uls.interface #34;" ext.centralNotice.bannerController"" skins.vector.js"]);}); \ n \ n \ n \ n \ n \ n \ n \ n \ n \ n \ n \ n \ n \ n \ n \ n \ n \ n \ n \ n \ n \ n \ n \ n \ nCastle \ n \ n来自维基百科,免费的百科全书\ n \ n \ n \ t \ t \ t \ t \ t跳转到:\ t \ t \ t \ t \ tnavigation,\ t \ t \ t \ t \ tsearch \ n \ n \ n \ n \ n \ n \ n英国的Bodiam城堡被充满水的护城河包围。\ n \ n \ n \ n \ n \ n \ n \ n \ n \ n \ n \ n \ n \ n \ n \ n \ n \ n \ n \ n \ n \ n \ n \ n \ n \ n \ n \ n \ n \ n \ n \ n城堡\ n \ n \ n \ n城堡(来自拉丁文castellum)是欧洲和中东制造的强化建筑在中世纪。人们争论城堡这个词是什么意思。然而,它通常意味着主或贵族的私人结构。这不同于一个不是家的堡垒,而是一个设防城镇,这是一个公共防御。大约900年来,城堡建成后,它们有许多不同的形状和不同的细节。\ nCastles在9和10世纪开始于欧洲。他们控制着周围的地方,并且可以帮助进攻和防守。武器可以从城堡中射击,也可以保护人们免受城堡中的敌人的攻击。然而,城堡也是权力的象征。它们可以用来控制周围的人和道路。\ n许多城堡最初都是用土和木建造的,经常使用体力劳动,然后用石头代替他们的防御。早期的城堡经常使用自然保护,并没有塔。然而,到了12世纪末和13世纪初,城堡变得越来越复杂。\ n
答案 0 :(得分:1)
file.writelines(str(soup.encode('UTF-8')))
有点疯狂,是:
str
)编码为二进制文件(bytes
)str
获取文本表示形式(所以它是你要键入的内容来重新创建二进制字节,但它不是原始二进制文件)writelines
迭代你给出的字符,str
按字符迭代)第3步是愚蠢而低效的,但大多是无害的。如果您将原始二进制文件写入为二进制写入打开的文件并且实际编写了bytes
对象,那么步骤#1就可以了。但#1和#2一起意味着像新行这样的东西会在输出中转换为文字\n
,而不是实际断开一条线。像é
这样的非ASCII内容输出为\xc3\xa9
,整个内容包含在b''
(或b""
)中。
你想要这样的东西:
# open with UTF-8 encoding (in case your system defaults to something else)
with open("TextOutput.txt", 'w', encoding='utf-8') as file:
# Get the text and write it as a single block
file.write(soup.get_text())