我想在Python中實現一個簡單的程序,它讀取rom網頁並將它們寫入文件。增量編號的消息大約有2000頁,但有些數字不見了。Python自動網頁下載,用戶名,密碼和Cookies
該網站的用戶名和密碼受到保護,我使用的是通常用於手動訪問的用戶名和密碼。我使用一些代碼示例與cookie處理我在Python的官方網站上找到,但是當我嘗試他們的網站,我試圖複製回覆
「你的瀏覽器不接受我們的cookies。查看(代碼0)「
很明顯,cookie存在問題,也許我沒有正確處理用戶名和密碼。有關以下代碼的任何建議?
import urllib2
import cookielib
import string
import urllib
def cook():
url="http://www.URL.com/message/"
cj = cookielib.LWPCookieJar()
authinfo = urllib2.HTTPBasicAuthHandler()
realm = "http://www.URL.com"
username = "ID"
password = "PSWD"
host = "http://www.URL.com/message/"
authinfo.add_password(realm, host, username, password)
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj), authinfo)
urllib2.install_opener(opener)
# Create request object
txheaders = { 'User-agent' : "Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)" }
try:
req = urllib2.Request(url, None, txheaders)
cj.add_cookie_header(req)
f = urllib2.urlopen(req)
except IOError, e:
print "Failed to open", url
if hasattr(e, 'code'):
print "Error code:", e.code
else:
print f
cook
url="http://www.URL.com/message/"
urllib.urlretrieve(url + '1', 'filename')
的替代,而不是一個解決方案:使用機械化庫http://wwwsearch.sourceforge.net/mechanize/ – 2010-12-13 01:10:10
也不是一個解決方案,但如果你正在尋找使用python抓取HTML並且不瞭解[BeautifulSoup](http://www.crummy.com/software/BeautifulSoup),它是非常有用的。 – Russ 2010-12-13 03:37:12