Scrapy NameError:未定义名称“filename”

2024-10-05 11:07:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我对Python完全陌生,我正在做一个关于web抓取的暑期独立实践项目,我试图使用Scrapy。到目前为止,我已经使用了http://doc.scrapy.org/en/1.1/intro/tutorial.html开始,但是由于spider教程没有按预期工作,我不得不即兴发挥。操作系统是win7

我试图复制教程代码并即兴创作,结果出现了以下错误:

File ..\spiders\dmoz_spider.py", line 16 in DmozSpider with open(filename, 
'wb') as f:
NameError: name 'filename' is not defined

代码是:

import scrapy

class DmozSpider(scrapy.Spider):
    name = "turo"
    allowed_domains = ["turotarjoo.com"]
    start_urls = [
        "http://turotarjoo.com/siipiravintola/",
        "http://turotarjoo.com/info/"
    ]

def parse(self, response):
    filename = None
    filename = response.url.split("/")[-1] + '.html'
    with open(filename, 'wb') as f:
        f.write(response.body)

谢谢你的帮助,如果我的第一个问题很难读懂,我很抱歉。如果你有任何启动python程序员或web抓取的提示,请告诉我。在


Tags: 代码comwebhttpresponsehtmlwith教程
1条回答
网友
1楼 · 发布于 2024-10-05 11:07:18
import scrapy
class DmozSpider(scrapy.Spider):
    name = "turo"
    allowed_domains = ["turotarjoo.com"]
    start_urls = [
        "http://turotarjoo.com/siipiravintola/",
        "http://turotarjoo.com/info/"
    ]

    def parse(self, response):
        filename = response.url.split("/")[-1] + '.html'
        with open(filename, 'wb') as f:
            f.write(response.body)

我只修复了凹痕,看起来效果不错。你能试试这个代码吗?在

相关问题 更多 >

    热门问题