Я пытаюсь получить HTML-код с веб-страниц. Однако не все URL-адреса написаны правильно. Большинство недопустимых URL-адресов в списке включают http, но теперь URL-адреса используют https. В некоторых отсутствует www, а в других - www. нужно добавить.
def repl_www_http(url):
x = url.replace("www.", "")
y = x.replace("http", "https")
return y
def repl_www(url):
y = url.replace("www.", "")
return y
def repl_http(url):
y = url.replace("http", "https")
return y
def repl_no_www(url):
y = url.replace("//", "//www.")
return y
def get_html(urllist):
for i in urllist:
html = ""
try:
html = requests.get(i)
html = html.text
return html
except requests.exceptions.ConnectionError:
try:
html = requests.get(repl_http(i))
html = html.text
print("replaced // with //www.")
except requests.exceptions.ConnectionError:
try:
html = requests.get(repl_http(i))
html = html.text
print("replaced http with https")
return html
except requests.exceptions.ConnectionError:
try:
html = requests.get(repl_www(i))
html = html.text
print("replaced www. with .")
return html
except requests.exceptions.ConnectionError:
try:
html = requests.get(repl_www_http(i))
html = html.text
print("replaced www with . and http with https")
return html
except requests.exceptions.ConnectionError:
return "no HTML found on this URL"
print("gethtml finished", html)
Я получаю вот такую ошибку:
Traceback (most recent call last): File "C:\replacer.py", line 76, in <module> html = get_html(i)
File "C:\replacer.py", line 37, in get_html html = requests.get(repl_http(i))
File "C:\Users\LorenzKort\AppData\Local\Programs\Python\Python37\lib\site-packages\requests-2.19.1-py3.7.egg\requests\api.py", line 72, in get
return request('get', url, params=params, **kwargs) File "C:\Users\LorenzKort\AppData\Local\Programs\Python\Python37\lib\site-packages\requests-2.19.1-py3.7.egg\requests\api.py", line 58, in request
return session.request(method=method, url=url, **kwargs) File "C:\Users\LorenzKort\AppData\Local\Programs\Python\Python37\lib\site-packages\requests-2.19.1-py3.7.egg\requests\sessions.py", line 498, in request
prep = self.prepare_request(req) File "C:\Users\LorenzKort\AppData\Local\Programs\Python\Python37\lib\site-packages\requests-2.19.1-py3.7.egg\requests\sessions.py", line 441, in prepare_request
hooks=merge_hooks(request.hooks, self.hooks),
File "C:\Users\LorenzKort\AppData\Local\Programs\Python\Python37\lib\site-packages\requests-2.19.1-py3.7.egg\requests\models.py",line 309, in prepare
self.prepare_url(url, params) File "C:\Users\LorenzKort\AppData\Local\Programs\Python\Python37\lib\site-packages\requests-2.19.1-py3.7.egg\requests\models.py",
line 383, in prepare_url
raise MissingSchema(error)requests.exceptions.MissingSchema: Invalid URL 'h': No schema supplied. Perhaps you meant http://h?
Как я могу решить эту проблему, чтобы исправить неправильный URL-адрес?
def repl_www_http (url): x = url.replace ("www.", "") y = x.replace ("http", "https") return y def repl_www (url): y = url.replace ("www . "," ") return y def repl_http (url): y = url.replace (" http "," https ") return y def repl_no_www (url): y = url.replace (" // "," // www. ") return y
Не могли бы вы вставить это в свой вопрос?
Я сделал! Это мой первый вопрос по Stackoverflow ;-)
Вы пытались распечатать анализируемый url? Возможно, ваша функция repl_http работает не так, как вы ожидаете, и сохраняет только h в качестве URL-адреса.






Проблема в том, что URL-адрес, переданный в request.get (), отправляет ошибки MissingSchema, и вы должны перехватить эту ошибку, когда поймаете ConnectionError.
Я думаю, вам следует использовать генератор для очистки вашего кода, потому что вам не следует вставлять такие операторы try / catch, как это.
def get_versions_url(my_url):
yield my_url
yield repl_www(my_url)
yield repl_http(my_url)
yield repl_http_www(my_url)
def get_html(urllist):
#use i only for indexes
for my_url in urllist:
for url_fixed in get_versions_url(my_url):
try:
# I dind't figure out why you return here and do not end first loop
return requests.get(url_fixed).text
except requests.exceptions.ConnectionError:
pass
except requests.exceptions.MissingSchema:
pass
Затем вы можете отлаживать свой генератор. Стараться сделать :
for url in fix_url(<your url>):
print(url)
Я думаю, что некоторые из ваших функций repl_ работают не так, как вы ожидаете.
Что такое
repl_http?