Zanurkuj w Pythonie/Wyciąganie danych z dokumentu HTML: Różnice pomiędzy wersjami

Usunięta treść Dodana treść
Piotr (dyskusja | edycje)
Nie podano opisu zmian
Piotr (dyskusja | edycje)
Nie podano opisu zmian
Linia 58:
 
'''Przykład 8.7. Korzystanie z <tt>urllister.py</tt>'''
<nowiki>
 
>>> import urllib, urllister
>>> usock = urllib.urlopen("http://diveintopython.org/")
Linia 79:
download/diveintopython-common-5.0.zip
... restpozostała ofczęść outputpominięta omitteddla for brevityczytelności ...
</nowiki>
 
# CallWywołujemy themetodę <tt>feed</tt> method,zdefiniowaną defined inw <tt>SGMLParser</tt>, toaby getprzekazać HTML into thedo parserparsera. <ref>The technical term for a parser like SGMLParser is a consumer: it consumes HTML and breaks it down. Presumably, the name feed was chosen to fit into the whole “consumer” motif. Personally, it makes me think of an exhibit in the zoo where there's just a dark cage with no trees or plants or evidence of life of any kind, but if you stand perfectly still and look really closely you can make out two beady eyes staring back at you from the far left corner, but you convince yourself that that's just your mind playing tricks on you, and the only way you can tell that the whole thing isn't just an empty cage is a small innocuous sign on the railing that reads, “Do not feed the parser.” But maybe that's just me. In any event, it's an interesting mental image.
</ref>. ItMetoda takesta abierze stringłańcuch znaków, whichktórym isw whattym przypadku będzie wartość zwrócona przez <tt>usock.read() returns</tt>.
# Podobnie jak pliki, powinieneś zamknąć swoje obiekty URL, kiedy już nie będą ci potrzebne.
# Like files, you should close your URL objects as soon as you're done with them.
# Powinieneś także zamknąć obiekt parsera, lecz z innego powodu. Podczas czytania danych przekazujemy je do parsera, lecz metoda <tt>feed</tt> nie gwarantuje, że wszystkie przekazane dane, zostały przetworzone. Parser może te dane zbuforować i czekać na dalszą porcję danych. Kiedy wywołamy <tt>close</tt>, mamy pewność, że bufor zostanie opróżniony i wszystko zostanie całkowicie sparsowane.
# You should close your parser object, too, but for a different reason. You've read all the data and fed it to the parser, but the feed method isn't guaranteed to have actually processed all the HTML you give it; it may buffer it, waiting for more. Be sure to call close to flush the buffer and force everything to be fully parsed.
# Ponieważ parser został zamknięty, więc parsowanie zostało zakończone i <tt>parser.urls</tt> zawiera listę wszystkich URL-ów, do których linkuje dokument HTML. (Twoje wyjście może wyglądać inaczej, ponieważ z biegiem czasu linki mogły ulec zmianie.)
# Once the parser is closed, the parsing is complete, and parser.urls contains a list of all the linked URLs in the HTML document. (Your output may look different, if the download links have been updated by the time you read this.)
 
'''Przypisy'''