【问题标题】:Using Beautiful Soup to get the full URL in source code使用 Beautiful Soup 获取源代码中的完整 URL
【发布时间】:2013-08-01 02:28:57
【问题描述】:

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

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

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

编辑: 如果给我&lt;a href = "/folder/big/a.jpg",您如何通过 python 或美丽的汤找出该 url 的起始部分?

【问题讨论】:

  • 你能发布html吗?

标签: python


【解决方案1】:
<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 模块中。

【讨论】:

  • (加入主机和相对/绝对URL见:stackoverflow.com/questions/8223939/…)。
  • @user2476540 那么a标签中指定的URL是错误的。我上面解释的是浏览器在看到带有前导斜杠的相对 URL 时的行为。
【解决方案2】:
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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-08
    • 1970-01-01
    • 2017-03-30
    相关资源
    最近更新 更多