10

所以我在看一些源代码,我遇到了这段代码

<img src="/gallery/2012-winners-finalists/HM_Watching%20birds2_Shane%20Conklin_MA_2012.jpg"

现在在源代码中,链接是蓝色的,当您单击它时,它会将您带到该图片所在的完整 URL,我知道如何使用 Beautiful Soup 获取 Python 源代码中显示的内容我想知道如何获取单击源代码中的链接后获得的完整 URL?

编辑:如果给<a href = "/folder/big/a.jpg"我你如何通过 python 或美丽的汤找出那个 url 的起始部分?

4

2 回答 2

28
<a href="/folder/big/a.jpg">

这是当前主机的绝对地址。因此,如果 HTML 文件位于http://example.com/foo/bar.html,则应用 url/folder/big/a.jpg将导致:

http://example.com/folder/big/a.jpg

即获取主机名并将新路径应用于它。

Python 具有urljoin为您执行此操作的内置函数:

>>> from urllib.parse import urljoin
>>> base = 'http://example.com/foo/bar.html'
>>> href = '/folder/big/a.jpg'
>>> urljoin(base, href)
'http://example.com/folder/big/a.jpg'

对于 Python 2,该函数位于urlparse模块内。

于 2013-08-01T16:24:04.810 回答
0
from bs4 import BeautifulSoup
import requests
import lxml

r = requests.get("http://example.com")

url = r.url  # this is base url
data = r.content  # this is content of page
soup = BeautifulSoup(data, 'lxml')
temp_url = soup.find('a')['href']  # you need to modify this selector

if temp_url[0:7] == "http://" or temp_url[0:8] == "https://" :  # if url have http://
        url = temp_url
else:
        url = url + temp_url


print url  # this is your full url
于 2019-10-11T05:43:41.080 回答