我有一个这样的 HTML 文件:
<div ckass="jokes-nav">
<ul>
<li><a href="http://link_1">Link 1</a></li>
<li><a href="http://link_2">Link 2</a></li>
</ul>
</div>
在文件夹 spiders 中,我有一个文件jacks.py,如下所示:
import scrapy
from demo_project.items import JokeItem
from scrapy.loader import ItemLoader
class JokesSpider(scrapy.Spider):
name = 'jokes'
start_urls = [
'http://www.laughfactory.com/jokes/'
]
def parse(self, response):
for joke in response.xpath("//div[@class='jokes-nav']/ul"):
l = ItemLoader(item = JokeItem(), selector = joke)
l.add_xpath('joke_title', ".//li/a/text()")
""" yield {
'joke_text': joke.xpath(".//div[@class='joke-text']/p").extract_first()
} """
yield l.load_item()
我在main.py中调用了 JokesSpider 类(该文件位于根目录),这是我的代码
from scrapy.crawler import CrawlerProcess
from demo_project.spiders.jokes import JokesSpider
process = CrawlerProcess(settings={
"FEEDS": {
"items.json": {"format": "json"},
},
})
process.crawl(JokesSpider)
process.start() # the script will block here until the crawling is finished
我想将数据写入 items.json,但是当我运行此代码时,items.json 中不包含任何内容,我该如何解决这个问题。非常感谢