在写 精通Scrapy网络爬虫 中的案例时,在写关于使用 FilesPipeline 案例时发现作者写的两行代码不怎么明白意思,在这做下笔记
代码如下:
from scrapy.pipelines.files import FilesPipeline
from urllib.parse import urlparse
from os.path import basename, dirname, join
# 实现一个FilesPipeline的子类,覆写file_path方法来实现所期望的文件命名规则
class MyFilePipeline(FilesPipeline):
def file_path(self, request, response=None, info=None):
path = urlparse(request.url).path
return join(basename(dirname(path)), basename(path))
python 中的 urlparse
urlparse模块主要是用于解析url中的参数 对url按照一定格式进行 拆分或拼接
1.urlparse.urlparse
将url分为6个部分,返回一个包含6个字符串项目的元组:协议、位置、路径、参数、查询、片段。
from urllib.parse import urlparse
url = 'https://matplotlib.org/mpl_examples/api/patch_collection.