Come posso leggere il contenuto di un URL con Python?


93

Quanto segue funziona quando lo incollo nel browser:

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

Ma quando provo a leggere l'URL con Python non succede nulla:

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

Devo codificare l'URL o c'è qualcosa che non vedo?

Risposte:


156

Per rispondere alla tua domanda:

import urllib

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

Hai bisogno di read()noreadline()

EDIT (2018-06-25): dal momento che Python 3, l'eredità è urllib.urlopen()stata sostituita da urllib.request.urlopen()(vedi note da https://docs.python.org/3/library/urllib.request.html#urllib.request.urlopen per i dettagli) .

Se stai usando Python 3, vedi le risposte di Martin Thoma o innm all'interno di questa domanda: https://stackoverflow.com/a/28040508/158111 (Python 2/3 compat) https://stackoverflow.com/a/45886824 / 158111 (Python 3)

Oppure prendi questa libreria qui: http://docs.python-requests.org/en/latest/ e usala seriamente :)

import requests

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

@KiranSubbaraman è davvero un buon progetto, dalle API alla struttura del codice
woozyking

Raccomando inoltre e incoraggio il programmatore a utilizzare il nuovo marchio requestsModule, il suo utilizzo si traduce in un codice più pitonico.
Hans Zimermann

1
Ricevo il seguente errore su 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'Sembra che non ci sia alcuna funzione urlopen in python 3.5. È stato rinominato? EDIT: Snippet nella risposta sotto risolve:from urllib.request import urlopen
LMD

@ user7185318 yes in Python 3 il urlibpacchetto ha visto alcuni refactoring e modifiche alle API. Aggiornerò la risposta per sottolineare su Python 2.
woozyking

cosa succede se il collegamento fornito richiede nome utente e password? Come si può quindi modificare il codice?
Dr. Essen

27

Per gli python3utenti, per risparmiare tempo, utilizzare il codice seguente,

from urllib.request import urlopen

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

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

So che ci sono diversi thread per l'errore:, Name Error: urlopen is not definedma ho pensato che questo potrebbe far risparmiare tempo.


Questo non è il modo migliore per leggere i dati da un URL utilizzando python3 perché perde i vantaggi dell'istruzione "with". Vedi la mia risposta: stackoverflow.com/a/56295038/908316
Jared

no questo non funzionerà sul ciclo while. una sola chiamata. che fa schifo se me lo chiedi
lone_coder

10

Una soluzione che funziona con Python 2.X e Python 3.X fa uso della libreria di compatibilità Python 2 e 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

Nessuna di queste risposte è molto buona per Python 3 (testato sull'ultima versione al momento di questo post).

Ecco come lo fai ...

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)

Quanto sopra è per i contenuti che restituiscono "utf-8". Rimuovi .decode ('utf-8') se vuoi che Python "indovina la codifica appropriata".

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


Grazie, il codice originale è stato scritto per Python 2, ma il tuo contributo qui è stato notato.
Helen Neely,

2

Possiamo leggere il contenuto html del sito Web come di seguito:

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

2
Questa è la stessa risposta di @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

L'URL dovrebbe essere una stringa:

import urllib

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

11
Sia "che" sono stringhe in Python
Leone

0

Ho usato il seguente codice:

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)

Grazie per questo snippet di codice, che potrebbe fornire un aiuto limitato e immediato. Una spiegazione adeguata migliorerebbe notevolmente il suo valore a lungo termine mostrando perché questa è una buona soluzione al problema e la renderebbe più utile ai futuri lettori con altre domande simili. Si prega di modificare la risposta di aggiungere qualche spiegazione, tra le ipotesi che hai fatto.
codedge

0

È possibile utilizzare requestse le beautifulsouplibrerie per leggere i dati su un sito Web. Basta installare queste due librerie e digitare il codice seguente.

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

Avrai tutte le informazioni necessarie sulla libreria.


helpè usato per visualizzare la documentazione di un dato modulo / classe / funzione. Penso che questa domanda
richieda

Grazie, ma questa è davvero una vecchia domanda e ho già ricevuto risposta. Grazie e benvenuto a stackoverflow.
Helen Neely,
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.