簡體   English   中英

Python從URL讀取頁面? 更好的文檔?

[英]Python read page from URL? Better documentation?

我在使用Python文檔時遇到了很多麻煩。 是否有類似Mozilla開發人員網絡的工具?

我正在做一個Python拼圖網站,我需要能夠閱讀該頁面的內容。 我在網站上看到以下內容:

import urllib2

urlStr = 'http://www.python.org/'
try:
  fileHandle = urllib2.urlopen(urlStr)
  str1 = fileHandle.read()
  fileHandle.close()
  print ('-'*50)
  print ('HTML code of URL =', urlStr)
  print ('-'*50)
except IOError:
  print ('Cannot open URL %s for reading' % urlStr)
  str1 = 'error!'

print (str1)

一直在說沒有urllib2模塊。

Python文檔說

The urllib module has been split into parts and renamed in Python 3.0 to urllib.request, urllib.parse, and urllib.error. The 2to3 tool will automatically adapt imports when converting your sources to 3.0. Also note that the urllib.urlopen() function has been removed in Python 3.0 in favor of urllib2.urlopen().

我也嘗試導入urllib.request,但它說urllib 2已定義... WTF在這里進行?

版本3.2.2

按照Dive into Python 3的建議使用urllib.request.open()

Python 3.2.1 (default, Jul 24 2011, 22:21:06) 
[GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import urllib.request
>>> urlStr = 'http://www.python.org/'
>>> fileHandle = urllib.request.urlopen(urlStr)
>>> print(fileHandle.read()[:100])
b'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtm'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM