python - 如何使用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 中不包含任何内容,我该如何解决这个问题。非常感谢
解决方案
您可以设置FEED_FORMAT
和FEED_URI
设置将数据保存在 json 文件中。
process = CrawlerProcess(settings={
'FEED_FORMAT': 'json',
'FEED_URI': 'items.json'
})
推荐阅读
- python - 如何将除最小值和最大值之外的所有元组值归零
- c - 二进制 & 的错误操作数无效(有 'int **' 和 'int *')
- python-3.x - 有没有办法在 Tkinter 中获得自定义形状的按钮?
- python - Django TransactionManagementError:select_for_update 不能在事务之外使用
- regex - Regexp_extract 在 Hive 中返回数据 2 次(重复)
- python - 混淆矩阵显示错误信息?
- azure-sql-database - 是否可以在 Azure SQL DB 中按用户实现行级安全性并在 ASP.Net 3.1 Web App 上访问用户特定的行集
- android - 为什么 waze deeplink 在 asynctask 中不起作用?
- plsql - 使用从数据库中选择将参数传递给 PL/SQL 过程
- webforms - c#, IIS 10, Web Forms, Forms Authentication, Bootstrap 4, Web API, Trying to Add Signalr - 在 signalr/hubs 上得到 404?