首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >BeautifulSoup .hyperlinks是如何工作的?

BeautifulSoup .hyperlinks是如何工作的?
EN

Stack Overflow用户
提问于 2014-01-23 16:11:39
回答 1查看 78关注 0票数 0

目前,我正在分析来自其他人的代码,现在我正在弄清楚BeautifulSoup.hyperlinks变量必须拥有什么。有人知道这方面的文件吗?我在官方网站上没有发现任何东西。问题是,当我打印soup.hyperlinks时,下面的代码会给出“None”:

代码语言:javascript
复制
from bs4 import BeautifulSoup

html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><b>The Dormouse's story</b></p>

<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>

<p class="intermezzo">this is a link: http://www.link.nl/
<a href="http://www.link.nl" title="link title" target="link target" class="link class">link label</a>
</p>

<p class="story">...</p>
"""

soup = BeautifulSoup(html_doc)

print soup.hyperlinks

我希望有人能帮我?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-01-23 16:14:46

BeautifulSoup对象没有.hyperlinks属性;也从来没有这样的东西。

相反,任何BeautifulSoup不识别的属性访问都会转化为对.find()的调用。soup.hyperlinks被解释为soup.find('hyperlinks'),搜索第一个<hyperlinks> HTML元素。因为没有这样的标记,所以将返回None

要查找HTML文档中的所有超链接,只需遍历所有a标记,仅限于具有href属性的标记:

代码语言:javascript
复制
print soup.find_all('a', href=True)

演示:

代码语言:javascript
复制
>>> soup.find_all('a', href=True)
[<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>, <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>, <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>, <a class="link class" href="http://www.link.nl" target="link target" title="link title">link label</a>]

您也可以获取所有href属性:

代码语言:javascript
复制
>>> [l['href'] for l in soup.find_all('a', href=True)]
[u'http://example.com/elsie', u'http://example.com/lacie', u'http://example.com/tillie', u'http://www.link.nl']
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21313544

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档