1
我目前正在嘗試使用Scrapey在python中創建一個簡單的爬蟲程序。我想要它做的是讀取鏈接列表並保存它們鏈接到的網站的html。現在,我可以獲取所有網址,但我無法弄清楚如何下載網頁。這裏是我的蜘蛛到目前爲止的代碼:用scrapy創建一個簡單的python爬蟲程序
from scrapy.spider import BaseSpider
from scrapy.selector import HtmlXPathSelector
from tutorial.items import BookItem
# Book scrappy spider
class DmozSpider(BaseSpider):
name = "book"
allowed_domains = ["learnpythonthehardway.org"]
start_urls = [
"http://www.learnpythonthehardway.org/book/",
]
def parse(self, response):
filename = response.url.split("/")[-2]
file = open(filename,'wb')
file.write(response.body)
file.close()
hxs = HtmlXPathSelector(response)
sites = hxs.select('//ul/li')
items = []
for site in sites:
item = BookItem()
item['title'] = site.select('a/text()').extract()
item['link'] = site.select('a/@href').extract()
items.append(item)
return items