1
次の例を考えてみましょう。URLの文字列を印刷するときにBS HTMLの解析 - &は無視されます
htmlist = ['<div class="portal" role="navigation" id="p-coll-print_export">',\
'<h3>Print/export</h3>',\
'<div class="body">',\
'<ul>',\
'<li id="coll-create_a_book"><a href="/w/index.php?title=Special:Book&bookcmd=book_creator&referer=Main+Page">Create a book</a></li>',\
'<li id="coll-download-as-rl"><a href="/w/index.php?title=Special:Book&bookcmd=render_article&arttitle=Main+Page&oldid=560327612&writer=rl">Download as PDF</a></li>',\
'<li id="t-print"><a href="/w/index.php?title=Main_Page&printable=yes" title="Printable version of this page [p]" accesskey="p">Printable version</a></li>',\
'</ul>',\
'</div>',\
'</div>',\
]
soup = __import__("bs4").BeautifulSoup("".join(htmlist), "html.parser")
for x in soup("a"):
print(x)
print(x.attrs)
print(soup.a.get_text())
私が終わる、(これらのそれぞれの名前(キーなど)とキーの値としてのコンテンツ())x
の属性の辞書に続いx
に等しいa
タグを、印刷するには、この短いスクリプトを期待していましたそのリンクのテキストが表示されます。
代わりに、出力は、私は、この出力を見つけ
<a href="/w/index.php?title=Special:Book&bookcmd=book_creator&referer=Main+Page">Create a book</a>
{'href': '/w/index.php?title=Special:Book&bookcmd=book_creator&referer=Main+Page'}
Create a book
<a href="/w/index.php?title=Special:Book&bookcmd=render_article&arttitle=Main+Page&oldid=560327612&writer=rl">Download as PDF</a>
{'href': '/w/index.php?title=Special:Book&bookcmd=render_article&arttitle=Main+Page&oldid=560327612&writer=rl'}
Create a book
<a accesskey="p" href="/w/index.php?title=Main_Page&printable=yes" title="Printable version of this page [p]">Printable version</a>
{'href': '/w/index.php?title=Main_Page&printable=yes', 'title': 'Printable version of this page [p]', 'accesskey': ['p']}
Create a book
問題があるさ:
print(soup.a.get_text())
ビットは常に最初のタグのテキストを出力します。print(x.attrs)
による辞書の出力で- 、キー
"href"
の値は、私がここで行方不明です何&.
が不足しているとどのように私は、所望の出力を得るのですか?
なぜ 'x.get_text()'を使用しないのですか?また '&'はhtmlでエンコードされた '&'のバージョンですので、心配しません。 –
@ t.m.adamもちろん、私は 'x'からテキストを得るべきです、ありがとう。しかし、私はまだ '& '部分が必要です。これは課題の一部であり、一致する出力が必要です。 –
@ t.m.adamクイック質問。ご覧のとおり、&を&に置き換えたソリューションを追加しましたが、リンクに正当なアンパサンドが含まれている可能性があるため、これが間違っている可能性があります。私の質問は: –