我是 Scrapy 的新手,正在尝试探索它的一些功能。我希望能够成功地创建一个抓取页面上的一组链接的抓取器——比如索引页面——并将整个页面保存为每个相应链接的 HTML 页面。 (逻辑是我可以稍后离线阅读内容,或者一旦我开始使用 Scrapy 的更高级功能就可以创建一个调度程序)
但是,我似乎卡在了这个练习上。我感觉这是我循环的错误方式——for 循环、回调或返回函数。
我的Spider.py代码如下:
import urlparse
import scrapy
from scrapy.http import Request
class BasicSpider(scrapy.Spider):
name = "basic"
allowed_domains = ["web"]
start_urls = (
'http://books.toscrape.com/',
)
def parse(self, response):
# My Link Extractor
next_selector = response.xpath(
'//*[@class="nav nav-list"]/li/ul/li/a/@href'
)
for url in next_selector.extract():
yield Request(urlparse.urljoin(response.url, url),
callback=self.parse_item)
def parse_item(self, response):
# My Page Saver
filename = response.url.split("/")[-1] + '.html'
with open(filename, 'wb') as f:
f.write(response.body)
return
如果我按照所需的 XPath 提取特定项目,我可以让#My Link Extractor 工作。我想我可以对整个事情进行 XPath >>>response.xpath('html').extract()...但似乎有更好的方法?
而且我可以获取#My Page Saver 以将单个链接的页面保存为 HTML,如 Download a full page with scrapy 所采用的那样.
但是,当我尝试整合两者时遇到了问题。我已经尝试修改 for 循环、回调和返回命令……但我遗漏了一些东西。
如有任何帮助,我们将不胜感激。
问候,
请您参考如下方法:
import urlparse
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.http import Request
class BooksSpider(scrapy.Spider):
name = "basic"
allowed_domains = ["toscrape"]
# ^ allowed domain should be name of domain that you wanna scrap
start_urls = (
'http://books.toscrape.com/',
)
def parse(self, response):
# My Link Extractor
next_page_urls = LinkExtractor(restrict_xpaths='//*[@class="next"]').extract_links(response)
# This is how we use LinkExtractor or you can create spider Rule for next page.
# Read more about LinkExtractor form https://doc.scrapy.org/en/latest/topics/link-extractors.html
for next_page in next_page_urls:
yield Request(next_page.url,callback=self.parse_item)
def parse_item(self, response):
# My Page Saver
filename = response.url.split("/")[-1] + '.html'
with open(filename, 'wb') as f:
f.write(response.body)
return
希望对你有帮助
