首页 > 解决方案 > 如何使用scrapy,xpath,python在锚标记中获取文本和href值

问题描述

我有一个这样的 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 中不包含任何内容,我该如何解决这个问题。非常感谢

标签: pythonweb-scrapingscrapyweb-mining

解决方案


您可以设置FEED_FORMATFEED_URI设置将数据保存在 json 文件中。

process = CrawlerProcess(settings={
    'FEED_FORMAT': 'json',
    'FEED_URI': 'items.json'
})

推荐阅读