[英]Downloading a sequence of webpages using Python
我對 Python [運行 2.7.x] 非常陌生,我正在嘗試從具有數千個鏈接的網頁下載內容。 這是我的代碼:
import urllib2
i = 1
limit = 1441
for i in limit:
url = 'http://pmindia.gov.in/content_print.php?nodeid='+i+'&nodetype=2'
response = urllib2.urlopen(url)
webContent = response.read()
f = open('speech'+i+'.html', 'w')
f.write(webContent)
f.close
相當基本,但我得到了這些錯誤中的一個或兩個,“int object is not iterable”或“cannot concatenate str and int”。 這些是本頁鏈接的可打印版本: http : //pmindia.gov.in/all-speeches.php (1400 個鏈接)。 但是節點 ID 從 1 到 1441,這意味着缺少 41 個數字(這是一個單獨的問題)。 最后最后一個問題:從長遠來看,在下載數千個鏈接對象時,有沒有辦法並行運行它們以提高處理速度?
嘗試這個:
for i in range(1, limit + 1):
...
range(M, N) 返回從 M(含)到 N(不含)的數字列表。 見https://docs.python.org/release/1.5.1p1/tut/range.html
您可能想考慮使用Scrapy或其他一些網絡爬行框架來幫助您解決這個問題。
您的代碼中有幾個錯誤。
通過這些修復,您的代碼看起來像
import urllib2
i = 1
limit = 1441
for i in xrange(1,limit+1):
url = 'http://pmindia.gov.in/content_print.php?nodeid='+repr(i)+'&nodetype=2'
response = urllib2.urlopen(url)
webContent = response.read()
f = open('speech'+repr(i)+'.html', 'w')
f.write(webContent)
f.close
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.