当前代码的python代码延续

2024-04-19 23:10:09 发布

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

我正在尝试从two.py文件导入代码,这是我当前代码在one.py上的延续,但是一直给我“exceptions.NameError: name 'main' is not defined”任何帮助都会很好。有没有其他方法可以继续anotherfile.py上的代码

one.py示例:

import scrapy
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.selector import HtmlXPathSelector
from crawler.items import CrawlertItem
from scrapy.contrib.spiders import SitemapSpider
from scrapy.log import *
from crawler.settings import *
from crawler.items import *
from urlparse import urlparse
import re

class GottaRent(CrawlSpider):
    name = "test"
    allowed_domains = ["www.example.com"]
    start_urls = ["http://www.example.com"]
    rules = [
        Rule(
            SgmlLinkExtractor(
                allow=(),
                deny=(r'/files/',)
            ),
            callback ="parse",
            follow=True
        )
    ]

def parse(self, response):
    hxs = HtmlXPathSelector(response)
    main = hxs.xpath("//body")
    for main in main:
        item = CrawlertItem()
        item['title'] = ''.join(main.xpath("//title//text()").extract())
        import sys, os
        sys.path.append(os.path.abspath('C:\crawler\__init__')) 
        from two import *
        yield item

two.py示例:

item['address'] = ''.join(main.xpath("//address//text()").extract())

Tags: 代码namefrompyimport示例mainitem
1条回答
网友
1楼 · 发布于 2024-04-19 23:10:09

通常,您应该在文件的开头执行所有导入,而不是在循环中。您的two.py示例抛出了该错误,因为模块不包含变量main(并且item也丢失)

当导入其他文件时,它应该只包含可以在其他文件中使用的函数和类。您不应该只是将代码“继续”到其他文件,而是可以将相关函数或类的组移动到那里

相关问题 更多 >