将域名转换为URL格式以进行URL解析

问题描述 投票:0回答:1

在我的Python脚本regd URL html.text解析中,对我的应用程序的输入是固定的,即域名。

但是我需要将该域名存储并处理为其URL格式。我认为不建议仅在域名前添加“ https://”。

如下所示,URL粘贴失败,因为它接收的是域格式而不是URL。

from urllib.request import Request, urlopen
import requests

url = 'xyz.com' # it is a domain name. But requires it to be in URL format to perform further parsing.

# Option 1
html=urlopen(url).read()

# Option 2
resp = requests.get(url)
html = resp.text

# Error encountered: Invalid URL.

将域名转换为URL格式的好方法是什么?

python python-3.x url dns urlopen
1个回答
1
投票

如果要确定"http://"+url"https://"+url是否正常工作,则可以同时检查两者:

from urllib.request import urlopen
from urllib.error import URLError

url = 'yourpage.com'
try:
  html=urlopen("https://"+url).read()
except URLError:
  html=urlopen("http://"+url).read()
© www.soinside.com 2019 - 2024. All rights reserved.