Python으로 URL의 내용을 어떻게 읽을 수 있습니까?


93

브라우저에 붙여 넣으면 다음이 작동합니다.

http://www.somesite.com/details.pl?urn=2344

하지만 Python으로 URL을 읽으려고하면 아무 일도 일어나지 않습니다.

 link = 'http://www.somesite.com/details.pl?urn=2344'
 f = urllib.urlopen(link)           
 myfile = f.readline()  
 print myfile

URL을 인코딩해야합니까, 아니면 보이지 않는 것이 있습니까?

답변:


156

질문에 답하려면 :

import urllib

link = "http://www.somesite.com/details.pl?urn=2344"
f = urllib.urlopen(link)
myfile = f.read()
print(myfile)

당신은 할 필요가 read()없습니다readline()

수정 (2018-06-25) : Python 3 이후 레거시 urllib.urlopen()가로 대체되었습니다 urllib.request.urlopen()(자세한 내용은 https://docs.python.org/3/library/urllib.request.html#urllib.request.urlopen의 메모 참조). .

Python 3을 사용하는 경우 다음 질문에서 Martin Thoma 또는 innm의 답변을 참조하십시오. https://stackoverflow.com/a/28040508/158111(Python 2/3 compat) https://stackoverflow.com/a/45886824 / 158111 (Python 3)

또는 http://docs.python-requests.org/en/latest/ 여기에서이 라이브러리를 가져 와서 진지하게 사용하십시오 :)

import requests

link = "http://www.somesite.com/details.pl?urn=2344"
f = requests.get(link)
print(f.text)

@KiranSubbaraman API에서 코드 구조에 이르기까지 정말 좋은 프로젝트입니다
— woozyking

또한 프로그래머에게 새로운 브랜드 requests모듈 을 사용하도록 권장하고 권장합니다 . 그 사용은 더 많은 Python 코드를 사용합니다.
— Hans Zimermann

1
python 3.5.2에서 다음 오류가 발생합니다 Traceback (most recent call last): File "/home/lars/parser.py", line 9, in <module> f = urllib.urlopen(link) AttributeError: module 'urllib' has no attribute 'urlopen'. python 3.5에는 urlopen 함수가없는 것 같습니다. 이름이 바뀌 었습니까? 편집 : 아래 답변의 스 니펫 해결 :from urllib.request import urlopen
— LMD

@ user7185318 예 Python 3에서 urlib패키지는 일부 리팩토링 및 API 변경을 보았습니다. 파이썬 2. 강조하기 위해 대답을 업데이 트됩니다
— woozyking

제공된 링크에서 사용자 이름과 비밀번호를 요청하면 어떻게됩니까? 그러면 코드를 어떻게 변경할 수 있습니까?
— Dr. Essen

27

를 들어 python3사용자, 시간을 절약 다음 코드를 사용하는,

from urllib.request import urlopen

link = "https://docs.scipy.org/doc/numpy/user/basics.broadcasting.html"

f = urlopen(link)
myfile = f.read()
print(myfile)

오류에 대한 다른 스레드가 있음을 알고 Name Error: urlopen is not defined있지만 시간을 절약 할 수 있다고 생각했습니다.


이것은 'with'문의 이점을 놓치기 때문에 python3을 사용하여 URL에서 데이터를 읽는 가장 좋은 방법이 아닙니다. 내 대답보기 : stackoverflow.com/a/56295038/908316
— Jared

이것은 while 루프에서 작동하지 않습니다. 한 번만 호출합니다. 당신이 저에게 물어 보면
— 짜증납니다

11

Python 2.X 및 Python 3.X에서 작동하는 솔루션은 Python 2 및 3 호환성 라이브러리를 사용합니다 six.

from six.moves.urllib.request import urlopen
link = "http://www.somesite.com/details.pl?urn=2344"
response = urlopen(link)
content = response.read()
print(content)

10

이 답변 중 어느 것도 Python 3에 적합하지 않습니다 (이 게시물 당시 최신 버전에서 테스트 됨).

이것이 당신이하는 방법입니다 ...

import urllib.request

try:
   with urllib.request.urlopen('http://www.python.org/') as f:
      print(f.read().decode('utf-8'))
except urllib.error.URLError as e:
   print(e.reason)

위 내용은 'utf-8'을 반환하는 내용입니다. 파이썬이 "적절한 인코딩을 추측"하게하려면 .decode ( 'utf-8')를 제거하십시오.

문서 : https://docs.python.org/3/library/urllib.request.html#module-urllib.request


감사합니다. 원본 코드는 Python 2 용으로 작성되었지만 여기에 귀하의 기여가 기록되었습니다.
— Helen Neely

2

다음과 같이 웹 사이트 html 내용을 읽을 수 있습니다.

from urllib.request import urlopen
response = urlopen('http://google.com/')
html = response.read()
print(html)

2
이 @innm에서 대답과 동일
— PeyM87

1
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Works on python 3 and python 2.
# when server knows where the request is coming from.

import sys

if sys.version_info[0] == 3:
    from urllib.request import urlopen
else:
    from urllib import urlopen
with urlopen('https://www.facebook.com/') as \
    url:
    data = url.read()

print data

# When the server does not know where the request is coming from.
# Works on python 3.

import urllib.request

user_agent = \
    'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.7) Gecko/2009021910 Firefox/3.0.7'

url = 'https://www.facebook.com/'
headers = {'User-Agent': user_agent}

request = urllib.request.Request(url, None, headers)
response = urllib.request.urlopen(request)
data = response.read()
print data

0

URL은 문자열이어야합니다.

import urllib

link = "http://www.somesite.com/details.pl?urn=2344"
f = urllib.urlopen(link)           
myfile = f.readline()  
print myfile

11
파이썬에서 둘 다 '와'된 문자열
— 레오

0

다음 코드를 사용했습니다.

import urllib

def read_text():
      quotes = urllib.urlopen("https://s3.amazonaws.com/udacity-hosted-downloads/ud036/movie_quotes.txt")
      contents_file = quotes.read()
      print contents_file

read_text()

0
# retrieving data from url
# only for python 3

import urllib.request

def main():
  url = "http://docs.python.org"

# retrieving data from URL
  webUrl = urllib.request.urlopen(url)
  print("Result code: " + str(webUrl.getcode()))

# print data from URL 
  print("Returned data: -----------------")
  data = webUrl.read().decode("utf-8")
  print(data)

if __name__ == "__main__":
  main()

0
from urllib.request import urlopen

# if has Chinese, apply decode()
html = urlopen("https://blog.csdn.net/qq_39591494/article/details/83934260").read().decode('utf-8')
print(html)

제한적이고 즉각적인 도움을 제공 할 수있는이 코드 스 니펫에 감사드립니다. 적절한 설명은 크게이 문제에 대한 좋은 해결책이 왜 보여 장기적인 가치를 향상 것이고, 다른 유사한 질문을 미래의 독자들에게 더 유용 할 것입니다. 제발 편집 당신이 만든 가정 등 일부 설명을 추가 할 답변을.
— codedge

0

requests및 beautifulsoup라이브러리를 사용 하여 웹 사이트에서 데이터를 읽을 수 있습니다 . 이 두 라이브러리를 설치하고 다음 코드를 입력하십시오.

import requests
import bs4
help(requests)
help(bs4)

도서관에 대해 필요한 모든 정보를 얻을 수 있습니다.


help주어진 모듈 / 클래스 / 함수에 대한 문서를 보는 데 사용됩니다. 이 질문은 응답 내용을 보는 방법을 요구한다고 생각합니다
— Panagiotis Simakis

감사합니다.하지만 이것은 정말 오래된 질문이며 이미 답변을 받았습니다. 감사합니다. stackoverflow에 오신 것을 환영합니다.
— Helen Neely
당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.