我目前正在尝试使用 Scrapey 在 python 中制作一个简单的爬虫。我想要它做的是阅读链接列表并保存它们链接到的网站的 html。现在,我能够获取所有的 URL,但我无法弄清楚如何下载该页面。到目前为止,这是我的蜘蛛的代码:
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