如何从代码中提取“title”属性?

2024-05-16 10:16:42 发布

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

我对Python有点陌生,我正在尝试理解如何从下面的代码中提取'title='属性。我一直在尝试使用beautifulsoup,但老实说,任何将工作对我是好的。你知道吗

<a class="image-link" href="/new-jersey/communities/holiday-city-at-berkeley" title="Holiday City at Berkeley"><div class="lazyload pulse out exited" style="height:auto"><div class="placeholder"><svg class="svg-placeholder-component" height="100%" viewbox="0 0 400 225" width="100%"><use xlink:href="#lazyload-placeholder"></use></svg></div></div></a>

我试过all[0].find_all('a', "title")all[0].find_all("title"),都返回了'[]'。你知道吗

<a class="image-link" href="/new-jersey/communities/holiday-city-at-berkeley" title="Holiday City at Berkeley"><div class="lazyload pulse out exited" style="height:auto"><div class="placeholder"><svg class="svg-placeholder-component" height="100%" viewbox="0 0 400 225" width="100%"><use xlink:href="#lazyload-placeholder"></use></svg></div></div></a>

Tags: svgimagedivnewtitleuselinkall
1条回答
网友
1楼 · 发布于 2024-05-16 10:16:42

您可以使用CSS选择器提取所需的元素:

from bs4 import BeautifulSoup

html = '<a class="image-link" href="/new-jersey/communities/holiday-city-at-berkeley" title="Holiday City at Berkeley"><div class="lazyload pulse out exited" style="height:auto"><div class="placeholder"><svg class="svg-placeholder-component" height="100%" viewbox="0 0 400 225" width="100%"><use xlink:href="#lazyload-placeholder"></use></svg></div></div></a>'
soup = BeautifulSoup(html, 'lxml')

for a in soup.select('a[title]'):
    print(a['title'])

印刷品:

Holiday City at Berkeley

相关问题 更多 >