я пытаюсь отправить запрос на этот URL: URL сайта
И сделайте простое чтение страницы со следующим кодом:
import requests
url_1 = 'http://www.dsit.org.ir/?cmd=page&Cid=92&title=Kontakt&lang=fa'
print(requests.get(url_1).text)
Но я получаю эту ошибку:
requests.exceptions.ConnectionError: HTTPConnectionPool(host='www.srgfesrsergserg.com', port=80): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x0000008EC69AAA90>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed'))
Этот сайт очень простой и не имеет специальных мер безопасности. Кроме того, я просил его только один раз
Все в порядке, и я очень легко открываю эту страницу с помощью Request-html, но я не знаю, в чем здесь проблема!
Добавьте заголовки.
Замаскируйте браузер.
import requests
headers = {
'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36'}
url_1 = 'http://www.dsit.org.ir/?cmd=page&Cid=92&title=Kontakt&lang=fa'
print(requests.get(url=url_1, headers=headers).text)
F12 Network
-> F5 -> Request Headers
Нажмите любой после этого, там пользовательский агент
Без проблем. Мне понравилось помогать вам.
да, я нашел это, но я хочу знать, для какого браузера этот заголовок?
У всех по-разному, я получаю это прямо из своего браузера.
Это происходит, когда вы отправляете слишком много запросов на общедоступный IP-адрес https://www.dsit.org.ir
. Как видите, это вызвано какой-то причиной, которая не разрешает/блокирует доступ к отображению общедоступных IP-адресов с помощью https://www.dsit.org.ir
. Одним из лучших решений является следующий скрипт Python, который вычисляет общедоступный IP-адрес любого домена и создает это сопоставление с файлом /etc/hosts.
import re
import socket
import subprocess
from typing import Tuple
ENDPOINT = 'https://anydomainname.example.com/'
ENDPOINT = 'https://www.dsit.org.ir/'
def get_public_ip() -> Tuple[str, str, str]:
"""
Command to get public_ip address of host machine and endpoint domain
Returns
-------
my_public_ip : str
Ip address string of host machine.
end_point_ip_address : str
Ip address of endpoint domain host.
end_point_domain : str
domain name of endpoint.
"""
# bash_command = """host myip.opendns.com resolver1.opendns.com | \
# grep "myip.opendns.com has" | awk '{print $4}'"""
# bash_command = """curl ifconfig.co"""
# bash_command = """curl ifconfig.me"""
bash_command = """ curl icanhazip.com"""
my_public_ip = subprocess.getoutput(bash_command)
my_public_ip = re.compile("[0-9.]{4,}").findall(my_public_ip)[0]
end_point_domain = (
ENDPOINT.replace("https://", "")
.replace("http://", "")
.replace("/", "")
)
end_point_ip_address = socket.gethostbyname(end_point_domain)
return my_public_ip, end_point_ip_address, end_point_domain
def set_etc_host(ip_address: str, domain: str) -> str:
"""
A function to write mapping of ip_address and domain name in /etc/hosts.
Ref: https://stackoverflow.com/questions/38302867/how-to-update-etc-hosts-file-in-docker-image-during-docker-build
Parameters
----------
ip_address : str
IP address of the domain.
domain : str
domain name of endpoint.
Returns
-------
str
Message to identify success or failure of the operation.
"""
bash_command = """echo "{} {}" >> /etc/hosts""".format(ip_address, domain)
output = subprocess.getoutput(bash_command)
return output
if __name__ == "__main__":
my_public_ip, end_point_ip_address, end_point_domain = get_public_ip()
output = set_etc_host(ip_address=end_point_ip_address, domain=end_point_domain)
print("My public IP address:", my_public_ip)
print("ENDPOINT public IP address:", end_point_ip_address)
print("ENDPOINT Domain Name:", end_point_domain )
print("Command output:", output)
Вы можете вызвать приведенный выше скрипт перед запуском нужной функции :)
WOOOW, это потрясающе, его работа хороша, братан, спасибо. Можете ли вы сказать, для какого браузера и системы он предназначен?