在 python 中抓取绝对 URL 而不是相对路径

Scrape the absolute URL instead of a relative path in python

我正在尝试从 HTML 代码中获取所有 href,并将其存储在列表中以供将来处理,例如:

示例URL:www.example-页面-xl.com

 <body>
    <section>
    <a href="/helloworld/index.php"> Hello World </a>
    </section>
 </body>

我正在使用以下代码列出 href:

import bs4 as bs4
import urllib.request

sauce = urllib.request.urlopen('https:www.example-page-xl.com').read()
soup = bs.BeautifulSoup(sauce,'lxml')

section = soup.section

for url in section.find_all('a'):
    print(url.get('href'))

但是我想将 URL 存储为: www.example-page-xl.com/helloworld/index.php 而不仅仅是 /helloworld/index.php

的相对路径

Appending/joining 不需要带有相对路径的 URL,因为当我加入 URL 和相对路径时,动态链接可能会有所不同。

简而言之,我想抓取绝对 URL 而不是单独的相对路径(并且不加入)

urllib.parse.urljoin() 可能会有所帮助。它执行连接,但它很聪明,可以处理相对路径和绝对路径。请注意,这是 python 3 代码。

>>> import urllib.parse
>>> base = 'https://www.example-page-xl.com'

>>> urllib.parse.urljoin(base, '/helloworld/index.php') 
'https://www.example-page-xl.com/helloworld/index.php'

>>> urllib.parse.urljoin(base, 'https://www.example-page-xl.com/helloworld/index.php')
'https://www.example-page-xl.com/helloworld/index.php'

在这种情况下urlparse.urljoin可以帮助你。你应该像这样修改你的代码 -

import bs4 as bs4
import urllib.request
from urlparse import  urljoin

web_url = 'https:www.example-page-xl.com'
sauce = urllib.request.urlopen(web_url).read()
soup = bs.BeautifulSoup(sauce,'lxml')

section = soup.section

for url in section.find_all('a'):
    print urljoin(web_url,url.get('href'))

这里 urljoin 管理绝对和相对路径。

我认为提到的解决方案 是最可靠的。

import urllib.parse

def base_url(url, with_path=False):
    parsed = urllib.parse.urlparse(url)
    path   = '/'.join(parsed.path.split('/')[:-1]) if with_path else ''
    parsed = parsed._replace(path=path)
    parsed = parsed._replace(params='')
    parsed = parsed._replace(query='')
    parsed = parsed._replace(fragment='')
    return parsed.geturl()