【问题标题】:Unable to get correct link in BeautifulSoup无法在 BeautifulSoup 中获得正确的链接
【发布时间】:2010-07-23 08:11:52
【问题描述】:

我正在尝试解析一些 HTML,我想提取与特定模式匹配的链接。我正在使用带有正则表达式的find 方法,但它没有给我正确的链接。这是我的sn-p。谁能告诉我我做错了什么?

from BeautifulSoup import BeautifulSoup
import re

html = """
<div class="entry">
    <a target="_blank" href="http://www.rottentomatoes.com/m/diary_of_a_wimpy_kid/">RT</a>
    <a target="_blank" href="http://www.imdb.com/video/imdb/vi2496267289/">Trailer</a> &ndash; 
    <a target="_blank" href="http://www.imdb.com/title/tt1196141/">IMDB</a> &ndash; 
</div>
"""

soup = BeautifulSoup(html)
print soup.find('a', href = re.compile(r".*title/tt.*"))['href']

我应该得到第二个链接,但 BS 总是返回第一个链接。第一个链接的href 甚至与我的正则表达式都不匹配,为什么它会返回它?

谢谢。

【问题讨论】:

  • 我已从 BeautifulSoup 导入 BeautifulSoup 进行更正。如果没有,它不应该工作。然后它返回第三个链接。我认为它工作正常。
  • 由于某种原因它似乎不起作用。它总是给出第一个链接 - http://www.rottentomatoes.com/m/diary_of_a_wimpy_kid/
  • 它也适用于我(BS v3.1.0.1)。我得到了第三个链接。你的版本是什么?

标签: python beautifulsoup


【解决方案1】:

find 只返回第一个 &lt;a&gt; 标记。你想要findAll

【讨论】:

    【解决方案2】:

    无法回答您的问题,但无论如何您(最初)发布的代码有导入拼写错误。改变

    import BeautifulSoup
    

    from BeautifulSoup import BeautifulSoup
    

    然后,您的输出(使用 beautifulsoup 3.1.0.1 版)将是:

    http://www.imdb.com/title/tt1196141/
    

    【讨论】:

    • 我的错。在我的电脑上测试它时,我在不同的位置有 BS,当我在这里复制粘贴代码时,我匆忙修改了import,因此出现了错字。我会进行编辑。问题仍然存在。它没有给我正确的链接。
    猜你喜欢
    • 2018-03-03
    • 2021-03-17
    • 1970-01-01
    • 1970-01-01
    • 2019-02-25
    • 1970-01-01
    • 1970-01-01
    • 2021-03-28
    • 2018-01-03
    相关资源
    最近更新 更多