HOWTO · Python

AttributeError: 모듈 Urllib에 속성 요청이 없습니다.

urllib 모듈을 완전히 가져온 다음 하위 모듈 요청을 속성으로 액세스하는 대신 상위 모듈 urllib에서 하위 모듈 요청을 가져와야 합니다.

이 페이지의 내용

Python의 urllib.request는 독립적인 모듈이므로 urllib는 이 상황에서 구현할 수 없습니다. 모듈에 여러 하위 모듈이 있는 경우 각각을 개별적으로 로드하면 비용이 많이 들고 프로그램과 관련 없는 항목에 문제가 발생할 수 있습니다.

Python은 가져오기를 사용하는 모듈이 가져오기를 자체적으로 사용하여 객체의 일부로 만들기 때문에 가져오기를 캐시합니다.

Python에서 AttributeError: module 'urllib'에 'request' 속성이 없습니다.

이 오류는 URL 라이브러리를 가져와 URL 링크를 열려고 할 때 Python에서 일반적인 예외입니다. 이 오류를 이해하기 위해 예를 들어 보겠습니다.

코드 예:

import urllib

request = urllib.request.Request("http://www.python.org")

출력:

AttributeError: module 'urllib' has no attribute 'request'

이와 같은 패키지를 사용할 때 때때로 필요한 모듈을 가져올 수 있습니다. urllib 모듈은 url의 작은 부분만 필요하기 때문에 모든 것을 로드할 필요가 없습니다.

가져오기 url은 전체 라이브러리에 액세스합니다. 그것이 오류를 표시하는 이유입니다.

Python에서 AttributeError: module 'urllib'에 'request' 속성이 없습니다. 수정

import urllib.request as urllib와 같이 가져오거나 import urllib.request urllib.request.urlopen('http://www.python.org',timeout=1)을 사용할 수 있습니다.

import urllib.request

with urllib.request.urlopen("http://www.python.org") as url:
    s = url.read()
    print(s)

출력:

<!doctype html>
<head>
    <meta charset="utf-8">
'
'
'
'
from urllib.request import Request, urlopen


def get_page_content(url, head):

    req = Request(url, headers=head)
    return urlopen(req)


url = "https://example.com"
head = {
    "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.84 Safari/537.36",
    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
    "Accept-Charset": "ISO-8859-1,utf-8;q=0.7,*;q=0.3",
    "Accept-Encoding": "none",
    "Accept-Language": "en-US,en;q=0.8",
    "Connection": "keep-alive",
    "refere": "https://example.com",
    "cookie": """your cookie value ( you can get that from your web page) """,
}

data = get_page_content(url, head).read()
print(data)

출력:

<!doctype html>\n<html>\n<head>\n    <title>Example Domain</title>\n\n    <meta charset="utf-8" />\n
'
'
'
href="https://www.iana.org/domains/example">More information...</a></p>\n</div>\n</body>\n</html>\n'

urllib 모듈을 완전히 가져온 다음 하위 모듈 요청을 속성으로 액세스하는 대신 상위 모듈 urllib에서 하위 모듈 요청을 가져와야 합니다.

import urllib print(urllib.request)는 작동하지 않지만 from urllib import request print(request) 및 import urllib.request는 모두 성공합니다.