【问题标题】:In what way beautiful soup works differenty in fetching links?Beautifulsoup 在获取链接方面的工作方式有何不同?
【发布时间】:2015-02-28 22:22:08
【问题描述】:

Insted 使用beautiful soup 为什么通过查找以<a href=" 开头的所有字符串实例来获取 html 内容并提取所有链接并不明智。 如果beautiful soup无法使用,还有什么方法可以提取链接?

【问题讨论】:

  • 为什么不能使用BeautifulSoup?你有什么条件?谢谢。

标签: python string url hyperlink beautifulsoup


【解决方案1】:

这是因为仅查找以

开头的链接是不够的
<a href="#">

利用类、id 或 HTML5 数据属性的 HTML 中的超链接可能有不同的变体,例如:

<a class="myclass id="the-id" data-tip="a tip" href="#">

使用 Beautiful Soup 可以让你在 Python 中非常简单地做到这一点,尤其是如果你有 HTML 和 CSS 的背景:

# src is the html of the web page.
soup = BeautifulSoup(src)

linkElements = soup.select('a.someclass')

if len(linkElements) > 0:
    for alinktag in linkElements:
        print alinktag['href']

另外,如果 HTML 是像下面这样的树形结构,Beautiful soup 可以很容易的将元素提取出来:

<div class="parent">
    <div class="child">
        <a class="linkclass" href="http://www.google.com">first link</a>
    </div>
    <div class="child">
        <a class="linkclass" href="http://www.yahoo.com">second link</a>
    </div>
</div>

美汤代号:

linkElements = soup.select('parent a.linkclass')

如果你正在寻找 Python 中 Beautiful Soup 的替代品,Quora 上有很好的讨论。

【讨论】:

  • 如果柜台问题没有超出范围,我想知道这汤有多美?
  • 反问是什么意思?
  • 漂亮的解析 URL 是如何避免所有的 &lt;a href="# 和什么的。
  • 我认为 Anzel 已经部分回答了这个问题。来自 Beautiful Soup 文档,“Beautiful Soup 位于流行的 Python 解析器(如 lxml 和 html5lib)之上”。因此它实际上并不使用正则表达式或字符串比较。它所做的是解析底层 XML 或 HTML 结构,然后读取属性或元素。在超链接的情况下,底层解析器读取 标记的属性(参见 Anzel 使用纯 xml 的示例 - “print a.attrib”)。
  • 已编辑关于 Beautiful Soup 的答案,对于具有 html 和 css 背景的用户而言,学习曲线较低。
【解决方案2】:

也许其他人可能不喜欢我的回答,但 BeautifulSoup 并不是操纵 html 内容的唯一方法。事实上,BeautifulSoup 本身 这样做,是底层的 HTML Parser 完成这项工作。

您可以使用lxml(甚至BeautifulSoup 也推荐它)甚至只是Python 的标准库xml/html 解析器模块来解析html 内容并对其进行操作。

这里举一个我从@maskie 那里得到的例子(对不起,我懒得做假人了):

使用 xml 模块的示例:

import xml.etree.ElementTree as ET

s = '''<div class="parent">
           <div class="child">
               <a class="linkclass" href="http://www.google.com">first link</a>
           </div>
           <div class="child">
               <a class="linkclass" href="http://www.yahoo.com">second link</a>
           </div>
       </div>'''

html = ET.fromstring(s)

for a in html.findall('.//a[@class="linkclass"]'):
    print a.attrib

{'href': 'http://www.google.com', 'class': 'linkclass'}
{'href': 'http://www.yahoo.com', 'class': 'linkclass'}

您可以使用 Python 标准库 urllib 或出色的 requests 模块从网络上简单地获取 html 内容。我经常进行网络抓取,而且大部分时间我只使用 requestslxml 并且它们做得很好。

NO 你不需要 BeautifulSoup 来从 html 中提取内容,我会说它只是让操作 html 内容更容易(对于某些人来说) .

我的回答是是的,您可以使用任何称职的 HTML Parser 来按照您的建议操作 html 内容,并且仍然可以完成工作。

【讨论】:

    猜你喜欢
    • 2022-01-26
    • 2021-07-22
    • 1970-01-01
    • 2023-01-24
    • 2018-06-01
    • 2017-09-08
    • 1970-01-01
    • 2019-02-27
    • 2021-11-26
    相关资源
    最近更新 更多