簡體   English   中英

使用 Python 下載一系列網頁

[英]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或其他一些網絡爬行框架來幫助您解決這個問題。

您的代碼中有幾個錯誤。

  1. 你得到了錯誤的語法。 當您調用 for 循環時,您需要向它傳遞一個可以迭代的對象。 這可以是列表或生成器
  2. 將數字添加到字符串將不起作用。 您需要使用例如 repr 進行轉換

通過這些修復,您的代碼看起來像

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

現在,如果您想真正進行網絡抓取,我建議您查看一些包,例如lxmlrequests

暫無
暫無

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

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