Python Beautifulsoup 解析 'a' 标签和'h'时没有链接

2024-04-26 07:52:45 发布

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

抱歉,如果有重复,我搜索了,但找不到答案。 我正在写一个scraper来刮取web服务器提供的默认目录索引页。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(<a href="Mysong2.mkv">),但是当指向文本时,它会在浏览器的状态栏(http://127.0.0.1/Mysongs/Mysong2.ogg)中显示链接

我试着用beauthoulsoup提取url,就像这样

^{pr2}$

我不能像http://127.0.0.1/Mysongs/Mysong2.ogg那样得到链接,而只能得到<a href="Mysong1.mkv">Mysong1.mp3</a> 10-May-2016 07:24

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

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

或者有更好的方法来得到这个吗?在

编辑::当前输出为

Mysong1.mp3
Mysong2.ogg

预期产量:

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

Tags: ofhttpindextitle链接htmlmp3head
1条回答
网友
1楼 · 发布于 2024-04-26 07:52:45

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

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

使用这个:

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

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

相关问题 更多 >