使用python元素树我想找到所有的ti

2024-05-14 18:47:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python中的xml新手,下面的xml文本中有这个xml,我正在尝试提取这个xml中的所有标题。我只成功地得到了元素。你知道吗

我卡住了,下面是我的代码。我需要帮助:

import xml.etree.ElementTree as ET

xml_text = '''<!DOCTYPE html>\n<html class="client-nojs" lang="en" dir="ltr">\n<head>\n<meta charset="UTF-8"/>\n<title>Fitzroy, South Australia - Wikipedia</title>\n<script>document.documentElement.className = document.documentElement.className.replace( /(^|\\s)client-nojs(\\s|$)/, "$1client-js$2" );</script>\n<script>(window.RLQ=window.RLQ||[]).push(function(){mw.config.set({"wgCanonicalNamespace":"","wgCanonicalSpecialPageName":false,"wgNamespaceNumber":0,"wgPageName":"Fitzroy,_South_Australia","wgTitle":"Fitzroy, South Australia","wgCurRevisionId":845266952,"wgRevisionId":845266952,"wgArticleId":3748581,"wgIsArticle":true,"wgIsRedirect":false,"wgAction":"view","wgUserName":null,"wgUserGroups":["*"],"wgCategories":["Use dmy dates from October 2012","Articles with short description","Coordinates on Wikidata","Suburbs of Adelaide"],"wgBreakFrames":false,"wgPageContentLanguage":"en","wgPageContentModel":"wikitext","wgSeparatorTransformTable":["",""],"wgDigitTransformTable":["",""],"wgDefaultDateFormat":"dmy","wgMonthNames":["","January","February","March","April","May","June","July","August","September","October","November","December"],"wgMonthNamesShort":["","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],"wgRelevantPageName":"Fitzroy,_South_Australia","wgRelevantArticleId":3748581,"wgRequestId":"WzEP8gpAIC4AAJfxgiQAAADI","wgIsProbablyEditable":true,"wgRelevantPageIsProbablyEditable":true,"wgRestrictionEdit":[],"wgRestrictionMove":[],"wgFlaggedRevsParams":{"tags":{}},"wgStableRevisionId":null,"wgCategoryTreePageCategoryOptions":"{\\"mode\\":0,\\"hideprefix\\":20,\\"showcount\\":true,\\"namespaces\\":false}","wgWikiEditorEnabledModules":[],"wgBetaFeaturesFeatures":[],"wgMediaViewerOnClick":true,"wgMediaViewerEnabledByDefault":true,"wgPopupsShouldSendModuleToUser":true,"wgPopupsConflictsWithNavPopupGadget":false,"wgVisualEditor":{"pageLanguageCode":"en","pageLanguageDir":"ltr","pageVariantFallbacks":"en","usePageImages":true,"usePageDescriptions":true},"wgPreferredVariant":"en","wgMFExpandAllSectionsUserOption":true,"wgMFEnableFontChanger":true,"wgMFDisplayWikibaseDescriptions":{"search":true,"nearby":true,"watchlist":true,"tagline":false},"wgRelatedArticles":null,"wgRelatedArticlesUseCirrusSearch":true,"wgRelatedArticlesOnlyUseCirrusSearch":false,"wgULSCurrentAutonym":"English","wgNoticeProject":"wikipedia","wgCentralNoticeCookiesToDelete":[],"wgCentralNoticeCategoriesUsingLegacy":["Fundraising","fundraising"],"wgCoordinates":{"lat":-34.897,"lon":138.59},"wgWikibaseItemId":"Q5455681","wgScoreNoteLanguages":{"arabic":"\xd8\xa7\xd9\x84\xd8\xb9\xd8\xb1\xd8\xa8\xd9\x8a\xd8\xa9","catalan":"catal\xc3\xa0","deutsch":"Deutsch","english":"English","espanol":"espa\xc3\xb1ol","italiano":"italiano","nederlands":"Nederlands","norsk":"norsk","portugues":"portugu\xc3\xaas","suomi":"suomi","svenska":"svenska","vlaams":"West-Vlams"},"wgScoreDefaultNoteLanguage":"nederlands","wgCentralAuthMobileDomain":false,"wgCodeMirrorEnabled":true,"wgVisualEditorToolbarScrollOffset":0,"wgVisualEditorUnsupportedEditParams":["undo","undoafter","veswitched"],"wgEditSubmitButtonLabelPublish":true});mw.loader.state({"ext.gadget.charinsert-styles":"ready","ext.globalCssJs.user.styles":"ready","ext.globalCssJs.site.styles":"ready","site.styles":"ready","noscript":"ready","user.styles":"ready","ext.globalCssJs.user":"ready","ext.globalCssJs.site":"ready","user":"ready","user.options":"ready","user.tokens":"loading","ext.cite.styles":"ready","mediawiki.legacy.shared":"ready","mediawiki.legacy.commonPrint":"ready","wikibase.client.init":"ready","ext.visualEditor.desktopArticleTarget.noscript":"ready","ext.uls.interlanguage":"ready","ext.wikimediaBadges":"ready","mediawiki.skinning.interface":"ready","skins.vector.styles":"ready"});mw.loader.implement("user.tokens@1dqfd7l",function($,jQuery,require,module){/*@nomin*/mw.user.tokens.set({"editToken":"+\\\\","patrolToken":"+\\\\","watchToken":"+\\\\","csrfToken":"+\\\\"});\n});mw.loader.load(["ext.cite.a11y","site","mediawiki.page.startup","mediawiki.user","mediawiki.hidpi","mediawiki.page.ready","mediawiki.toc","mediawiki.searchSuggest","ext.gadget.teahouse","ext.gadget.ReferenceTooltips","ext.gadget.watchlist-notice","ext.gadget.DRN-wizard","ext.gadget.charinsert","ext.gadget.refToolbar","ext.gadget.extra-toolbar-buttons","ext.gadget.switcher","ext.centralauth.centralautologin","mmv.head","mmv.bootstrap.autostart","ext.popups","ext.visualEditor.desktopArticleTarget.init","ext.visualEditor.targetLoader","ext.eventLogging.subscriber","ext.wikimediaEvents","ext.navigationTiming","ext.uls.eventlogger","ext.uls.init","ext.uls.compactlinks","ext.uls.interface","ext.3d","ext.centralNotice.geoIP","ext.centralNotice.startUp","skins.vector.js"]);});</script>\n<link rel="stylesheet" href="/w/load.php?debug=false&amp;lang=en&amp;modules=ext.cite.styles%7Cext.uls.interlanguage%7Cext.visualEditor.desktopArticleTarget.noscript%7Cext.wikimediaBadges%7Cmediawiki.legacy.commonPrint%2Cshared%7Cmediawiki.skinning.interface%7Cskins.vector.styles%7Cwikibase.client.init&amp;only=styles&amp;skin=vector"/>\n<script async="" src="/w/load.php?debug=false&amp;lang=en&amp;modules=startup&amp;only=scripts&amp;skin=vector"></script>\n<meta name="ResourceLoaderDynamicStyles" content=""/>\n<link rel="stylesheet" href="/w/load.php?debug=false&amp;lang=en&amp;modules=ext.gadget.charinsert-styles&amp;only=styles&amp;skin=vector"/>\n<link rel="stylesheet" href="//creativecommons.org/licenses/by-sa/3.0/"/>\n<link rel="canonical" href="https://en.wikipedia.org/wiki/Fitzroy,_South_Australia"/>\n<link rel="dns-prefetch" href="//login.wikimedia.org"/>\n<link rel="dns-prefetch" <a href="/wiki/Local_government_areas_of_South_Australia" title="Local government areas of South Australia">LGA(s)</a></th>\n<td><a href="/wiki/City_of_Prospect" title="City of Prospect">City of Prospect</a></td>\n</tr>\n<tr>\n<th scope="row" style="width:40%; background-color:#f9e2d2;"><a href="/wiki/Electorates_of_the_Australian_states_and_territories" title="Electorates of the Australian states and territories">State electorate(s)</a></th>\n<td><a href="/wiki/Electoral_district_of_Adelaide" title="Electoral district of Adelaide">Adelaide</a></td>\n</tr>\n<tr>\n<th scope="row" style="width:40%; background-color:#f9e2d2;"><a href="/wiki/Divisions_of_the_Australian_House_of_Representatives" title="Divisions of the Australian House of Representatives">Federal Division(s)</a></th>\n<td><a href="/wiki/Division_of_Adelaide" title="Division of Adelaide">Adelaide</a></td>\n</tr>\n<tr>\n<td colspan="2" style="text-align:center">\n<table cellpadding="4" cellspacing="3" style="width:100%; border: 1px #ddd solid;">\n<tr class="mergedrow">\n<td colspan="3" style="background-color:#f0f0ff;padding: 2px 0px; text-align:center;"><b><a href="/wiki/List_of_Adelaide_suburbs" title="List of Adelaide suburbs">Suburbs</a> around Fitzroy:</b></td>\n</tr>\n<tr class="mergedrow">\n<td style="text-align:center; padding: 3px 0px; width:33%;"><a href="/wiki/Renown_Park,_South_Australia" title="Renown Park, South Australia">Renown Park</a></td>\n<td style="text-align:center; padding: 3px 0px; width:34%;"><a href="/wiki/Prospect,_South_Australia" title="Prospect, South Australia">Prospect</a></td>\n<td style="text-align:center; padding: 3px 0px; width:33%;"><a href="/wiki/Prospect,_South_Australia" title="Prospect, South Australia">Prospect</a></td>\n</tr>\n<tr class="mergedrow">\n<td style="text-align:center; vertical-align: middle; padding: 3px 0px; width:33%;"><a href="/wiki/Ovingham,_South_Australia" title="Ovingham, South Australia">Ovingham</a></td>\n<td style="text-align:center; vertical-align: middle; padding: 3px 0px; width:34%;font-weight:bold;">Fitzroy</td>\n<td style="text-align:center; vertical-align: middle; padding: 3px 0px; width:33%;"><a href="/wiki/Thorngate,_South_Australia" title="Thorngate, South Australia">Thorngate</a></td>\n</tr>\n<tr class="mergedrow">\n<td style="text-align:center; padding: 3px 0px; width:33%;"><a href="/wiki/Ovingham,_South_Australia" title="Ovingham, South Australia">Ovingham</a></td>\n<td style="text-align:center; padding: 3px 0px; width:34%;"><i><a href="/wiki/Adelaide_Park_Lands" title="Adelaide Park Lands">Adelaide Park Lands</a></i></td>\n<td style="text-align:center; padding: 3px 0px; width:33%;"><i><a href="/wiki/Adelaide_Park_Lands" title="Adelaide Park Lands">Adelaide Park Lands</a></i></td>\n</tr>\n<tr>\n<td colspan="2"></td>\n</tr>\n</table>\n</td>\n</tr>\n</table>\n<p><b>Fitzroy</b> is an upper class, inner northern <a href="/wiki/Suburb" title="Suburb">suburb</a> of <a href="/wiki/Adelaide" title="Adelaide">Adelaide</a> 4&#160;km (2.5&#160;mi) from the <a href="/wiki/Adelaide_city_centre" title="Adelaide city centre">Adelaide city centre</a>, in the state of <a href="/wiki/South_Australia" title="South Australia">South Australia</a>, within the <a href="/wiki/City_of_Prospect" title="City of Prospect">City of Prospect</a>. It is adjacent to <a href="/wiki/Prospect,_South_Australia" title="Prospect, South Australia">Prospect</a>, <a href="/wiki/Ovingham,_South_Australia" title="Ovingham, South Australia">Ovingham</a>, <a href="/wiki/Thorngate,_South_Australia" title="Thorngate, South Australia">Thorngate</a> and, across the <a href="/wiki/Adelaide_Park_Lands" title="Adelaide Park Lands">Adelaide Park Lands</a>, <a href="/wiki/North_Adelaide" title="North Adelaide">North Adelaide</a>.</p>\n<p></p>\n<div id="toc" class="toc">\n<div class="toctitle" lang="en" dir="ltr">\n<h2>Contents</h2>\n</div>\n<ul>\n<li class="toclevel-1 tocsection-1"><a href="#Location"><span class="tocnumber">1</span> <span class="toctext">Location</span></a></li>\n<li class="toclevel-1 tocsection-2"><a href="#Features"><span class="tocnumber">2</span> <span class="toctext">Features</span></a></li>\n<li class="toclevel-1 tocsection-3"><a href="#Transport"><span class="tocnumber">3</span> <span class="toctext">Transport</span></a></li>\n<li class="toclevel-1 tocsection-4"><a href="#References"><span class="tocnumber">4</span> <span class="toctext">References</span></a></li>\n</ul>\n</div>\n<p></p>\n<h2><span class="mw-headline" id="Location">Location</span><span class="mw-editsection"><span class="mw-editsection-bracket">[</span><a href="/w/index.php?title=Fitzroy,_South_Australia&amp;action=edit&amp;section=1" title="Edit section: Location">edit</a><span class="mw-editsection-bracket">]</span></span></h2>\n<p>Fitzroy is bounded on the west by Cotton Street, on the south by <a href="/wiki/City_Ring_Route,_Adelaide" title="City Ring Route, Adelaide">Fitzroy Terrace</a>, on the east by <a href="/wiki/Prospect_Road,_Adelaide" title="Prospect Road, Adelaide">Prospect Road</a> and on the north by Whinham and Halstead streets. Fitzroy is essentially a residential suburb, overlooking the northern <a href="/wiki/Adelaide_parklands" class="mw-redirect" title="Adelaide parklands">Adelaide parklands</a>.<sup id="cite_ref-PLB_1-1" class="reference"><a href="#cite_note-PLB-1">[1]</a></sup></p>\n<h2><span class="mw-headline" id="Features">Features</span><span class="mw-editsection"><span class="mw-editsection-bracket">[</span><a href="/w/index.php?title=Fitzroy,_South_Australia&amp;action=edit&amp;section=2" title="Edit section: Features">edit</a><span class="mw-editsection-bracket">]</span></span></h2>\n<div class="thumb tright">\n<div class="thumbinner" style="width:302px;"><a href="/wiki/File:Mormon_fitzroy.jpg" class="image"><img alt="" src="//upload.wikimedia.org/wikipedia/commons/thumb/c/cf/Mormon_fitzroy.jpg/300px-Mormon_fitzroy.jpg" width="300" height="152" class="thumbimage" srcset="//upload.wikimedia.org/wikipedia/commons/thumb/c/cf/Mormon_fitzroy.jpg/450px-Mormon_fitzroy.jpg 1.5x, //upload.wikimedia.org/wikipedia/commons/thumb/c/cf/Mormon_fitzroy.jpg/600px-Mormon_fitzroy.jpg 2x" data-file-width="640" data-file-height="325" /></a>\n<div class="thumbcaption">\n<div class="magnify"><a href="/wiki/File:Mormon_fitzroy.jpg" class="internal" title="Enlarge"></a></div>\nMormon meetinghouse in Fitzroy</div>\n</div>\n</div>\n<p>Aside from a <a href="/wiki/The_Church_of_Jesus_Christ_of_Latter-day_Saints" title="The Church of Jesus Christ of Latter-day Saints">Mormon</a> meetinghouse overlooking <a href="/wiki/Torrens_Road,_Adelaide" title="Torrens Road, Adelaide">Torrens Road</a>,<sup id="cite_ref-2" class="reference"><a href="#cite_note-2">[2]</a></sup> there are no non-residential facilities within the bounds of Fitzroy. The closest schools are in the northerly-adjacent and much larger <a href="/wiki/Prospect,_South_Australia" title="Prospect, South Australia">Prospect</a>.</p>\n<h2><span class="mw-headline" id="Transport">Transport</span><span class="mw-editsection"><span class="mw-editsection-bracket">[</span><a href="/w/index.php?title=Fitzroy,_South_Australia&amp;action=edit&amp;section=3" title="Edit section: Transport">edit</a><span class="mw-editsection-bracket">]</span></span></h2>\n<p>The main north-south arterial traffic routes of <a href="/wiki/Churchill_Road,_Adelaide" class="mw-redirect" title="Churchill Road, Adelaide">Churchill Road</a> and Prospect Road pass to the west and east of Fitzroy, and the <a href="/wiki/City_Ring_Route,_Adelaide" title="City Ring Route, Adelaide">City Ring Route</a> passes along the southern edge of the suburb. Prospect Road is served by the G10 bus service and Churchill Road by the 235 bus service. The <a href="/wiki/Ovingham_railway_station" title="Ovingham railway station">Ovingham railway station</a> to the west is within easy walking distance of all parts of Fitzroy.</p>\n<h2><span class="mw-headline" id="References">References</span><span class="mw-editsection"><span class="mw-editsection-bracket">[</span><a href="/w/index.php?title=Fitzroy,_South_Australia&amp;action=edit&amp;section=4" title="Edit section: References">edit</a><span class="mw-editsection-bracket">]</span></span></h2>\n<div class="reflist" style="list-style-type: decimal;">\n<div class="mw-references-wrap">\n<ol class="references">\n<li id="cite_note-PLB-1"><span class="mw-cite-backlink">^ <a href="#cite_ref-PLB_1-0"><sup><i><b>a</b></i></sup></a> <a href="#cite_ref-PLB_1-1"><sup><i><b>b</b></i></sup></a></span> <span class="reference-text"><cite class="citation web"><a rel="nofollow" class="external text" href="http://maps.sa.gov.au/plb">"Placename Details: Fitzroy"</a>. <i>Property Location Browser</i>. <a href="/wiki/Government_of_South_Australia" title="Government of South Australia">Government of South Australia</a>. 11 March 2009. SA0024187<span class="reference-accessdate">. Retrieved <span class="nowrap">8 December</span> 2017</span>. <q>Derivation of Name: Fitzroy, near Melbourne; Other Details: Decision made on 18/9/1944 by City of Prospect to adopt this name as a suburb name.</q></cite><span title="ctx_ver=Z39.88-2004&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Ajournal&amp;rft.genre=unknown&amp;rft.jtitle=Property+Location+Browser&amp;rft.atitle=Placename+Details%3A+Fitzroy&amp;rft.date=2009-03-11&amp;rft_id=http%3A%2F%2Fmaps.sa.gov.au%2Fplb&amp;rfr_id=info%3Asid%2Fen.wikipedia.org%3AFitzroy%2C+South+Australia" class="Z3988"><span style="display:none;">&#160;</span></span></span></li>\n<li id="cite_note-2"><span class="mw-cite-backlink"><b><a href="#cite_ref-2">^</a></b></span> <span class="reference-text"><cite class="citation web"><a rel="nofollow" class="external text" href="https://www.mormon.org.au/meetinghouse?address=Adelaide">"Prospect Ward: 28 Fitzroy Terrace"</a>. Church of Jesus Christ of Latter-day Saints<span class="reference-accessdate">. Retrieved <span class="nowrap">15 January</span> 2018</span>.</cite><span title="ctx_ver=Z39.88-2004&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Abook&amp;rft.genre=unknown&amp;rft.btitle=Prospect+Ward%3A+28+Fitzroy+Terrace&amp;rft.pub=Church+of+Jesus+Christ+of+Latter-day+Saints&amp;rft_id=https%3A%2F%2Fwww.mormon.org.au%2Fmeetinghouse%3Faddress%3DAdelaide&amp;rfr_id=info%3Asid%2Fen.wikipedia.org%3AFitzroy%2C+South+Australia" class="Z3988"><span style="display:none;">&#160;</span></span></span></li>\n</ol>\n</div>\n</div>\n<div role="navigation" class="navbox" aria-labelledby="Suburbs_of_the_City_of_Prospect" style="padding:3px">\n<table class="nowraplinks collapsible autocollapse navbox-inner" style="border-spacing:0;background:transparent;color:inherit">\n<tr>\n<th scope="col" class="navbox-title" colspan="2">\n<div class="plainlinks hlist navbar mini">\n<ul>\n<li class="nv-view"><a href="/wiki/Template:City_of_Prospect_suburbs" title="Template:City of Prospect suburbs"><abbr title="View this template" style=";;background:none transparent;border:none;-moz-box-shadow:none;-webkit-box-shadow:none;box-shadow:none;">v</abbr></a></li>\n<li class="nv-talk"><a href="/wiki/Template_talk:City_of_Prospect_suburbs" title="Template talk:City of Prospect suburbs"><abbr title="Discuss this template" style=";;background:none transparent;border:none;-moz-box-shadow:none;-webkit-box-shadow:none;box-shadow:none;">t</abbr></a></li>\n<li class="nv-edit"><a class="external text" href="//en.wikipedia.org/w/index.php?title=Template:City_of_Prospect_suburbs&amp;action=edit"><abbr title="Edit this template" style=";;background:none transparent;border:none;-moz-box-shadow:none;-webkit-box-shadow:none;box-shadow:none;">e</abbr></a></li>\n</ul>\n</div>\n<div id="Suburbs_of_the_City_of_Prospect" style="font-size:114%;margin:0 4em">Suburbs of the <a href="/wiki/City_of_Prospect" title="City of Prospect">City of Prospect</a></div>\n</th>\n</tr>\n<tr>\n<td colspan="2" class="navbox-list navbox-odd hlist" style="width:100%;padding:0px">\n<div style="padding:0em 0.25em">\n<ul>\n<li><a href="/wiki/Broadview,_South_Australia" title="Broadview, South Australia">Broadview</a></li>\n<li><a href="/wiki/Collinswood,_South_Australia" title="Collinswood, South Australia">Collinswood</a></li>\n<li><a class="mw-selflink selflink">Fitzroy</a></li>\n<li><a href="/wiki/Medindie_Gardens,_South_Australia" title="Medindie Gardens, South Australia">Medindie Gardens</a></li>\n<li><a href="/wiki/Nailsworth,_South_Australia" title="Nailsworth, South Australia">Nailsworth</a></li>\n<li><a href="/wiki/Prospect,_South_Australia" title="Prospect, South Australia">Prospect</a></li>\n<li><a href="/wiki/Ovingham,_South_Australia" title="Ovingham, South Australia">Ovingham</a></li>\n<li><a href="/wiki/Sefton_Park,_South_Australia" title="Sefton Park, South Australia">Sefton Park</a></li>\n<li><a href="/wiki/Thorngate,_South_Australia" title="Thorngate, South Australia">Thorngate</a></li>\n</ul>\n</div>\n</td>\n</tr>\n</table>\n</div>\n<p><span style="font-size: small;"><span id="coordinates"><a href="/wiki/Geographic_coordinate_system" title="Geographic coordinate system">Coordinates</a>: <span class="plainlinks nourlexpansion"><a class="external text" href="//tools.wmflabs.org/geohack/geohack.php?pagename=Fitzroy,_South_Australia&amp;params=34.897_S_138.590_E_type:city_region:AU-SA"><span class="geo-default"><span class="geo-dms" title="Maps, aerial photos, and other data for this location"><span class="latitude">34\xc2\xb053\xe2\x80\xb249\xe2\x80\xb3S</span> <span class="longitude">138\xc2\xb035\xe2\x80\xb224\xe2\x80\xb3E</span></span></span><span class="geo-multi-punct">\xef\xbb\xbf / \xef\xbb\xbf</span><span class="geo-nondefault"><span class="geo-dec" title="Maps, aerial photos, and other data for this location">34.897\xc2\xb0S 138.590\xc2\xb0E</span><span style="display:none">\xef\xbb\xbf / <span class="geo">-34.897; 138.590</span></span></span></a></span></span></span></p>\n\n\n<!-- \nNewPP limit report\nParsed by mw1267\nCached time: 20180620022042\nCache expiry: 1900800\nDynamic content: false\nCPU time usage: 0.188 seconds\nReal time usage: 0.253 seconds\nPreprocessor visited node count: 1218/1000000\nPreprocessor generated node count: 0/1500000\nPost\xe2\x80\x90expand include size: 22900/2097152 bytes\nTemplate argument size: 1857/2097152 bytes\nHighest expansion depth: 12/40\nExpensive parser function count: 5/500\nUnstrip recursion depth: 0/20\nUnstrip post\xe2\x80\x90expand size: 2308/5000000 bytes\nNumber of Wikibase entities loaded: 1/400\nLua time usage: 0.087/10.000 seconds\nLua memory usage: 4.25 MB/50 MB\n-->\n<!--\nTransclusion expansion time report (%,ms,calls,template)\n100.00%  224.105      1 -total\n 51.82%  116.134      1 Template:Infobox_Australian_place\n 30.33%   67.966      1 Template:Infobox\n 19.13%   42.874      1 Template:Reflist\n 15.68%   35.131      2 Template:Cite_web\n 14.54%   32.579      1 Template:Use_dmy_dates\n 12.73%   28.539      2 Template:Convert\n 11.25%   25.222      1 Template:Short_description\n 10.37%   23.236      1 Template:Coord\n  9.21%   20.648      1 Template:Pagetype\n-->\n</div>\n<!-- Saved in parser cache with key enwiki:pcache:idhash:3748581-0!canonical and timestamp 20180620022042 and revision id 845266952\n -->\n<noscript><img src="//en.wikipedia.org/wiki/Special:CentralAutoLogin/start?type=1x1" alt="" title="" width="1" height="1" style="border: none; position: absolute;" /></noscript></div>\t\t\t\t\t<div class="printfooter">\n\t\t\t\t\t\tRetrieved from "<a dir="ltr" href="https://en.wikipedia.org/w/index.php?title=Fitzroy,_South_Australia&amp;oldid=845266952">https://en.wikipedia.org/w/index.php?title=Fitzroy,_South_Australia&amp;oldid=845266952</a>"\t\t\t\t\t</div>\n\t\t\t\t<div id="catlinks" class="catlinks" data-mw="interface"><div id="mw-normal-catlinks" class="mw-normal-catlinks"><a href="/wiki/Help:Category" title="Help:Category">Categories</a>: <ul><li><a href="/wiki/Category:Suburbs_of_Adelaide" title="Category:Suburbs of Adelaide">Suburbs of Adelaide</a></li></ul></div><div id="mw-hidden-catlinks" class="mw-hidden-catlinks mw-hidden-cats-hidden">Hidden categories: <ul><li><a href="/wiki/Category:Use_dmy_dates_from_October_2012" title="Category:Use dmy dates from October 2012">Use dmy dates from October 2012</a></li><li><a href="/wiki/Category:Articles_with_short_description" title="Category:Articles with short description">Articles with short description</a></li><li><a href="/wiki/Category:Coordinates_on_Wikidata" title="Category:Coordinates on Wikidata">Coordinates on Wikidata</a></li></ul></div></div>\t\t\t\t<div class="visualClear"></div>\n\t\t\t\t\t\t\t</div>\n\t\t</div>\n\t\t<div id="mw-navigation">\n\t\t\t<h2>Navigation menu</h2>\n\t\t\t<div id="mw-head">\n\t\t\t\t\t\t\t\t\t<div id="p-personal" role="navigation" class="" aria-labelledby="p-personal-label">\n\t\t\t\t\t\t<h3 id="p-personal-label">Personal tools</h3>\n\t\t\t\t\t\t<ul>\n\t\t\t\t\t\t\t<li id="pt-anonuserpage">Not logged in</li><li id="pt-anontalk"><a href="/wiki/Special:MyTalk" title="Discussion about edits from this IP address [n]" accesskey="n">Talk</a></li><li id="pt-anoncontribs"><a href="/wiki/Special:MyContributions" title="A list of edits made from this IP address [y]" accesskey="y">Contributions</a></li><li id="pt-createaccount"><a href="/w/index.php?title=Special:CreateAccount&amp;returnto=Fitzroy%2C+South+Australia" title="You are encouraged to create an account and log in; however, it is not mandatory">Create account</a></li><li id="pt-login"><a href="/w/index.php?title=Special:UserLogin&amp;returnto=Fitzroy%2C+South+Australia" title="You&#039;re encouraged to log in; however, it&#039;s not mandatory. [o]" accesskey="o">Log in</a></li>\t\t\t\t\t\t</ul>\n\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t\t<div id="left-navigation">\n\t\t\t\t\t\t\t\t\t\t<div id="p-namespaces" role="navigation" class="vectorTabs" aria-labelledby="p-namespaces-label">\n\t\t\t\t\t\t<h3 id="p-namespaces-label">Namespaces</h3>\n\t\t\t\t\t\t<ul>\n\t\t\t\t\t\t\t<li id="ca-nstab-main" class="selected"><span><a href="/wiki/Fitzroy,_South_Australia" title="View the content page [c]" accesskey="c">Article</a></span></li><li id="ca-talk"><span><a href="/wiki/Talk:Fitzroy,_South_Australia" rel="discussion" title="Discussion about the content page [t]" accesskey="t">Talk</a></span></li>\t\t\t\t\t\t</ul>\n\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t\t\t<div id="p-variants" role="navigation" class="vectorMenu emptyPortlet" aria-labelledby="p-variants-label">\n\t\t\t\t\t\t\t\t\t\t\t\t<input type="checkbox" class="vectorMenuCheckbox" aria-labelledby="p-variants-label" />\n\t\t\t\t\t\t<h3 id="p-variants-label">\n\t\t\t\t\t\t\t<span>Variants</span>\n\t\t\t\t\t\t</h3>\n\t\t\t\t\t\t<div class="menu">\n\t\t\t\t</div>\n\t\t\t\t<div id="right-navigation">\n\t\t\t\t\t\t\t\t\t\t<div id="p-views" role="navigation" class="vectorTabs" aria-labelledby="p-views-label">\n\t\t\t\t\t\t<h3 id="p-views-label">Views</h3>\n\t\t\t\t\t\t<ul>\n\t\t\t\t\t\t\t<li id="ca-view" class="collapsible selected"><span><a href="/wiki/Fitzroy,_South_Australia">Read</a></span></li><li id="ca-edit" class="collapsible"><span><a href="/w/index.php?title=Fitzroy,_South_Australia&amp;action=edit" title="Edit this page [e]" accesskey="e">Edit</a></span></li><li id="ca-history" class="collapsible"><span><a href="/w/index.php?title=Fitzroy,_South_Australia&amp;action=history" title="Past revisions of this page [h]" accesskey="h">View history</a></span></li>\t\t\t\t\t\t</ul>\n\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t\t\t<div id="p-cactions" role="navigation" class="vectorMenu emptyPortlet" aria-labelledby="p-cactions-label">\n\t\t\t\t\t\t<input type="checkbox" class="vectorMenuCheckbox" aria-labelledby="p-cactions-label" />\n\t\t\t\t\t\t<h3 id="p-cactions-label"><span>More</span></h3>\n\t\t\t\t\t\t<div class="menu">\n\t\t\t\t\t\t\t<ul>\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t</ul>\n\t\t\t\t\t\t</div>\n\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t\t\t<div id="p-search" role="search">\n\t\t\t\t\t\t<h3>\n\t\t\t\t\t\t\t<label for="searchInput">Search</label>\n\t\t\t\t\t\t</h3>\n\t\t\t\t\t\t<form action="/w/index.php" id="searchform">\n\t\t\t\t\t\t\t<div id="simpleSearch">\n\t\t\t\t\t\t\t\t<input type="search" name="search" placeholder="Search Wikipedia" title="Search Wikipedia [f]" accesskey="f" id="searchInput"/><input type="hidden" value="Special:Search" name="title"/><input type="submit" name="fulltext" value="Search" title="Search Wikipedia for this text" id="mw-searchButton" class="searchButton mw-fallbackSearchButton"/><input type="submit" name="go" value="Go" title="Go to a page with this exact name if it exists" id="searchButton" class="searchButton"/>\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t</form>\n\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t\t</div>\n\t\t\t</div>\n\t\t\t<div id="mw-panel">\n\t\t\t\t<div id="p-logo" role="banner"><a class="mw-wiki-logo" href="/wiki/Main_Page"  title="Visit the main page"></a></div>\n\t\t\t\t\t\t<div class="portal" role="navigation" id="p-navigation" aria-labelledby="p-navigation-label">\n\t\t\t<h3 id="p-navigation-label">Navigation</h3>\n\t\t\t<div class="body">\n\t\t\t\t\t\t\t\t<ul>\n\t\t\t\t\t<li id="n-mainpage-description"><a href="/wiki/Main_Page" title="Visit the main page [z]" accesskey="z">Main page</a></li><li id="n-contents"><a href="/wiki/Portal:Contents" title="Guides to browsing Wikipedia">Contents</a></li><li id="n-featuredcontent"><a href="/wiki/Portal:Featured_content" title="Featured content \xe2\x80\x93 the best of Wikipedia">Featured content</a></li><li id="n-currentevents"><a href="/wiki/Portal:Current_events" title="Find background information on current events">Current events</a></li><li id="n-randompage"><a href="/wiki/Special:Random" title="Load a random article [x]" accesskey="x">Random article</a></li><li id="n-sitesupport"><a href="https://donate.wikimedia.org/wiki/Special:FundraiserRedirector?utm_source=donate&amp;utm_medium=sidebar&amp;utm_campaign=C13_en.wikipedia.org&amp;uselang=en" title="Support us">Donate to Wikipedia</a></li><li id="n-shoplink"><a href="//shop.wikimedia.org" title="Visit the Wikipedia store">Wikipedia store</a></li>\t\t\t\t</ul>\n\t\t\t\t\t\t\t</div>\n\t\t</div>\n\t\t\t<div class="portal" role="navigation" id="p-interaction" aria-labelledby="p-interaction-label">\n\t\t\t<h3 id="p-interaction-label">Interaction</h3>\n\t\t\t<div class="body">\n\t\t\t\t\t\t\t\t<ul>\n\t\t\t\t\t<li id="n-help"><a href="/wiki/Help:Contents" title="Guidance on how to use and edit Wikipedia">Help</a></li><li id="n-aboutsite"><a href="/wiki/Wikipedia:About" title="Find out about Wikipedia">About Wikipedia</a></li><li id="n-portal"><a href="/wiki/Wikipedia:Community_portal" title="About the project, what you can do, where to find things">Community portal</a></li><li id="n-recentchanges"><a href="/wiki/Special:RecentChanges" title="A list of recent changes in the wiki [r]" accesskey="r">Recent changes</a></li><li id="n-contactpage"><a href="//en.wikipedia.org/wiki/Wikipedia:Contact_us" title="How to contact Wikipedia">Contact page</a></li>\t\t\t\t</ul>\n\t\t\t\t\t\t\t</div>\n\t\t</div>\n\t\t\t<div class="portal" role="navigation" id="p-tb" aria-labelledby="p-tb-label">\n\t\t\t<h3 id="p-tb-label">Tools</h3>\n\t\t\t<div class="body">\n\t\t\t\t\t\t\t\t<ul>\n\t\t\t\t\t<li id="t-whatlinkshere"><a href="/wiki/Special:WhatLinksHere/Fitzroy,_South_Australia" title="List of all English Wikipedia pages containing links to this page [j]" accesskey="j">What links here</a></li><li id="t-recentchangeslinked"><a href="/wiki/Special:RecentChangesLinked/Fitzroy,_South_Australia" rel="nofollow" title="Recent changes in pages linked from this page [k]" accesskey="k">Related changes</a></li><li id="t-upload"></body>\n</html>'''

root = ET.fromstring(xml_text).findall('.//')
print(root[0][1].text)

for elem in root:
    element = elem
    print(element)

Tags: ofdividtitlewikiliclassmw
1条回答
网友
1楼 · 发布于 2024-05-14 18:47:20

你差点就拿到了。我的建议是,您应该再次阅读xml.etree.ElementTree模块的文档。你知道吗

https://docs.python.org/3/library/xml.etree.elementtree.html

您正在使用XML解析器解析XML。这个Python模块允许您访问解析树的元素对象。每个元素对象都附带了一个属性字典。因此,对于每个元素,您可以看到是否有title属性。请看下面(注意:我对您的代码做了一些修改):

import xml.etree.ElementTree as ET

import requests
from bs4 import BeautifulSoup

# I am just getting the HTML source code for the web page here
r = requests.get('https://en.wikipedia.org/wiki/Fitzroy,_South_Australia')
soup = BeautifulSoup(r.content, 'html.parser')
xml_text = soup.prettify()

root = ET.fromstring(xml_text).findall('.//')
print(root[0][1].text)

for element in root:
    if 'title' in element.attrib:
        print(element.attrib['title'])

手动遍历树中的每个元素并测试title属性是否存在可能不是最有效的方法。更好的方法是使用XPath表达式。所以,在你的例子中,它看起来是这样的:

import xml.etree.ElementTree as ET

import requests
from bs4 import BeautifulSoup

# I am just getting the HTML source code for the web page here
r = requests.get('https://en.wikipedia.org/wiki/Fitzroy,_South_Australia')
soup = BeautifulSoup(r.content, 'html.parser')
xml_text = soup.prettify()

elements = ET.fromstring(xml_text).findall('.//*[@title]')
for element in elements:
    print(element.text)

我在上面链接的模块文档中都提到了这一点。下次一定要仔细阅读。你知道吗

相关问题 更多 >

    热门问题