Scrapy 和 Python 的麻烦:总是出现意想不到的缩进

数据挖掘 Python 数据集
2022-02-20 14:10:47

我正在尝试构建一个能够从本地 craigslist 中提取数据以获取工作的scrapy bot,并具有递归功能以允许收集联系人数据。最终,我希望将所有这些数据放入一个 .CVS 文件中。我已经阅读了 Learning Python the Hard Way以及Automating the hard stuff with Python 的大部分内容,但是我仍然是个新手。在尝试构建此脚本时,我参考了以下教程: Scrapy 的文档Michael Herman 的这篇博客文章我觉得好像我的代码只是有一个愚蠢的语法错误,但我太不知道该怎么做才能修复它。

这是蜘蛛的代码:

from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.selector import HtmlXPathSelector
from craigslist_sample.items import CraigslistSampleItem

class MySpider(CrawlSpider):
name = "craigs"
allowed_domains = ["sfbay.craigslist.org"]
start_urls = ["http://salem.craigslist.org/search/jjj"]
#Initially grab all of the urls up to where craigslist allows
#In this case, it's 2400 
for i in range(1, 24):
    start_urls.append(base_url + "s=" + str(i) + "00&")

rules = (
    Rule(SgmlLinkExtractor(allow=(), restrict_xpaths=('//a[@class="button next"]',)), callback="parse_items", follow= True),
)

def parse_items(self, response):
    hxs = HtmlXPathSelector(response)
    titles = hxs.xpath('//span[@class="pl"]')
    items = []
    for titles in titles:
        item = CraigslistSampleItem()
        item["title"] = titles.xpath("a/text()").extract()
        item["link"] = titles.xpath("a/@href").extract()
        item["email"] = titles.xpath("@anonemail").extract()
        items.append(item)
    return(items)

以下是我收到的确切错误:

*File "C:\Users\newfa\Documents\scripts\craigslist_sample\craigslist_sample\spiders\test.py", line 27
item["email"] = titles.xpath("@anonemail").extract()
^

IndentationError:意外缩进*

我确实知道缩进在 Python 中非常重要,但是我一直在尝试不同的缩进方法,并尝试了几种“美化”代码方法来尝试让它正确,这让我相信它可能是其他一些错误。

1个回答

经过片刻更多的工作,我能够解决自己的问题。错误原来是我在那里的代码中丢失的狂野“标签”标记。此外,我的“allowed_domains”部分很不稳定。这在下面的代码中都得到了纠正

 from scrapy.contrib.spiders import CrawlSpider, Rule
 from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
 from scrapy.selector import HtmlXPathSelector
 from craigslist_sample.items import CraigslistSampleItem

class MySpider(CrawlSpider):
name = "test"
allowed_domains = ["salem.craigslist.org"]
start_urls = ["http://salem.craigslist.org/search/jjj"]


rules = (
    Rule(SgmlLinkExtractor(allow=(), restrict_xpaths=('//a[@class="button next"]',)), callback="parse_items", follow= True),
)

def parse_items(self, response):
    hxs = HtmlXPathSelector(response)
    titles = hxs.xpath('//span[@class="pl"]')
    items = []
    for titles in titles:
       item = CraigslistSampleItem()
       item["title"] = titles.xpath("a/text()").extract()
       item["link"] = titles.xpath("a/@href").extract()
       item["email"] = titles.xpath("A/@anonemail").extract()
       items.append(item)
    return(items)

不幸的是,我仍然无法获取电子邮件、电话号码或描述数据——但是,由于这些问题与我提出的问题没有直接关系,因此可以公平地说它已得到回答。