【问题标题】:python beautifulsoup no link when parsing 'a' tag and href [duplicate]python beautifulsoup在解析'a'标签和href时没有链接[重复]
【发布时间】:2016-06-04 12:36:16
【问题描述】:

抱歉,如果有重复,我搜索但找不到答案。 我正在编写一个刮板来刮掉我的网络服务器提供的默认目录索引页面。 html看起来像这样

<html>
<head><title>Index of /Mysongs</title></head>
<body bgcolor="white">
<h1>Index of /Mysongs</h1><hr><pre><a href="../">../</a>
<a href="Mysong1.mkv">Mysong1.mp3</a>                        10-May-2016 07:24           183019
<a href="Mysong2.mkv">Mysong2.ogg</a>                        10-May-2016 07:27           177205

href 链接看起来只是一个文本,而不是 URL (&lt;a href="Mysong2.mkv"&gt;),但在指向文本时,它会在浏览器的状态栏中显示链接 (http://127.0.0.1/Mysongs/Mysong2.ogg)

我尝试使用 beautifulsoup 提取 url,像这样

#!/usr/bin/python

import httplib2
import sys
from BeautifulSoup import BeautifulSoup, SoupStrainer

http = httplib2.Http()
status, response = http.request(sys.argv[1])
for link in BeautifulSoup(response, parseOnlyThese=SoupStrainer('a')):
    print link.get('href')

我无法获得像http://127.0.0.1/Mysongs/Mysong2.ogg 这样的链接,但只能获得&lt;a href="Mysong1.mkv"&gt;Mysong1.mp3&lt;/a&gt; 10-May-2016 07:24

我应该使用sys.argv[1] 来构造href 链接吗

print sys.argv[1] + link.get('href')

或者有没有更好的方法来获得这个?

Edit:: 当前输出是

Mysong1.mp3
Mysong2.ogg

预期输出:

http://127.0.0.1/Mysong1.mp3
http://127.0.0.1/Mysong1.0gg

【问题讨论】:

  • 你到底想要什么输出?
  • 谢谢@AniMenon,我打算将这些网址传递给外部下载加速器,该加速器可以连续下载块。所以我在寻找网址,而不仅仅是纯文本。我可以通过连接基本 url 和文本来创建 url,但我想知道这是否是唯一的方法,并且有 pythonic 方式或模块支持。
  • 发布预期输出和当前输出。
  • 完成,@AniMenon。谢谢。
  • @init Beautiful soup 总是返回 href 中的任何内容,所以如果你想要这样的输出,那么添加基本 url 是你唯一的选择。

标签: python html beautifulsoup


【解决方案1】:

是的,您唯一的选择是添加基本网址。但不要这样添加:

print sys.argv[1] + link.get('href')

使用这个:

from urlparse import urljoin
urljoin('http://something.com/random/abc.html', '../../music/MySong.mp3')

在您的方法中,可能无法识别和处理相对路径,urljoin 会处理它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-24
    • 2016-12-03
    • 1970-01-01
    • 2012-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多