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からコード構造まで、本当に良いプロジェクトです
2015

また、プログラマーに新しいブランドのrequestsモジュールを使用することをお勧めします。これは、よりPythonicなコードに使用できます。
Hans Zimermann 2017年

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'Python3.5にはurlopen関数がないようです。名前が変更されましたか?編集:以下の回答のスニペットは解決します:from urllib.request import urlopen
LMD 2018年

@ user7185318はい、Python 3では、urlibパッケージにリファクタリングとAPIの変更がいくつか見られました。私は、Python 2を重視する答えを更新します
woozyking

提供されたリンクがユーザー名とパスワードを要求した場合はどうなりますか?次に、コードをどのように変更できますか?
エッセン博士

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ループでは機能しません。1回の呼び出しのみ。あなたが私に尋ねるならそれは
ひどい

10

Python2.XおよびPython3.Xで動作するソリューションは、Python2および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)

8

これらの答えはどれもPython3にはあまり適していません(この投稿の時点で最新バージョンでテストされています)。

これはあなたがそれをする方法です...

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」を返すコンテンツ用です。Pythonに「適切なエンコーディングを推測」させたい場合は、.decode( 'utf-8')を削除してください。

ドキュメント:https//docs.python.org/3/library/urllib.request.html#module-urllib.request


おかげで、元のコードはPython 2用に書かれましたが、ここでのあなたの貢献は注目されています。
ヘレンニーリー

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
'と "はどちらもPythonの文字列です
Leo

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ライブラリを使用して、Webサイト上のデータを読み取ることができます。これら2つのライブラリをインストールして、次のコードを入力するだけです。

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

ライブラリについて必要なすべての情報を入手できます。


help指定されたモジュール/クラス/関数のドキュメントを表示するために使用されます。質問は、回答の内容を表示する方法を求めていると思います
Panagiotis Simakis

ありがとう、しかしこれは本当に古い質問であり、すでに答えられています。おかげで、stackoverflowへようこそ。
ヘレンニーリー
弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.