108

ブラウザに貼り付けると、次のように動作します。

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をエンコードする必要がありますか、それとも表示されないものがありますか?

4

10 に答える 10

184

あなたの質問に答えるには:

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 以降、レガシーは (詳細についてはhttps://docs.python.org/3/library/urllib.request.html#urllib.request.urlopenのメモを参照してください)urllib.urlopen()に置き換えられました。 .urllib.request.urlopen()

Python 3 を使用している場合は、この質問内の Martin Thoma または innm による回答を参照して ください。 /158111 (パイソン 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)
于 2013-02-28T14:59:55.040 に答える
10

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)
于 2015-01-20T08:17:55.973 に答える
-1

URL は文字列である必要があります。

import urllib

link = "http://www.somesite.com/details.pl?urn=2344"
f = urllib.urlopen(link)           
myfile = f.readline()  
print myfile
于 2013-02-28T14:58:18.823 に答える
-1
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)
于 2020-05-16T07:59:27.640 に答える
-1

次のコードを使用しました。

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()
于 2017-08-22T11:00:39.113 に答える
-1
# 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()
于 2019-11-27T07:37:44.617 に答える