我有一个scrapy项目的例子。它几乎是默认的。它的文件夹结构:
craiglist_sample/
├── craiglist_sample
│ ├── __init__.py
│ ├── items.py
│ ├── pipelines.py
│ ├── settings.py
│ └── spiders
│ ├── __init__.py
│ ├── test.py
└── scrapy.cfg
当您将scrapy crawl craigs -o items.csv -t csv
写入Windows命令提示符时,它会将craiglist项目和链接写入控制台。
我想在main文件夹中创建一个example.py并将这些项打印到其中的python控制台。
我试过
from scrapy import cmdline
cmdline.execute("scrapy crawl craigs".split())
但它写的与windows shell输出相同。如何才能使其仅打印项目和列表?
test.py :
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.selector import HtmlXPathSelector
from craiglist_sample.items import CraiglistSampleItem
class MySpider(CrawlSpider):
name = "craigs"
## allowed_domains = ["sfbay.craigslist.org"]
## start_urls = ["http://sfbay.craigslist.org/npo/"]
allowed_domains = ["craigslist.org"]
start_urls = ["http://sfbay.tr.craigslist.org/search/npo?"]
##search\/npo\?s=
rules = (Rule (SgmlLinkExtractor(allow=('s=\d00',),restrict_xpaths=('//a[@class="button next"]',))
, callback="parse_items", follow= True),
)
def parse_items(self, response):
hxs = HtmlXPathSelector(response)
titles = hxs.select('//span[@class="pl"]')
## titles = hxs.select("//p[@class='row']")
items = []
for titles in titles:
item = CraiglistSampleItem()
item ["title"] = titles.select("a/text()").extract()
item ["link"] = titles.select("a/@href").extract()
items.append(item)
return(items)
答案 0 :(得分:0)
一种方法可能是关闭scrapy的默认shell输出并在parse_items函数中插入一个print命令。
1 - 关闭文件settings.py中的调试级别
LOG_ENABLED = False
有关Scrapy中日志记录级别的文档:http://doc.scrapy.org/en/latest/topics/logging.html
2 - 为您感兴趣的项目添加打印命令
for titles in titles:
item = CraiglistSampleItem()
item ["title"] = titles.select("a/text()").extract()
item ["link"] = titles.select("a/@href").extract()
items.append(item)
print item ["title"], item ["link"]
shell输出将是:
[u'执行助理'] [u' /eby/npo/4848086929.html']
[u' Direct Support Professional'] [u' /eby/npo/4848043371.html']
[u'职业顾问'] [u' /eby/npo/4848042572.html']
[u' Day Programvisor'] [u' /eby/npo/4848041846.html']
[u'教育专家'] [u' /eby/npo/4848040348.html']
[u'与GREENPEACE合作 - 基层非营利工作!']
[U' /eby/npo/4847984654.html']
编辑用于从脚本执行的代码
import os
os.system('scrapy crawl craigs > log.txt')
在python中执行行程序还有其他几种方法。 查看Executing command line programs from within python和Calling an external command in Python