python - 让 Scrapy 跟随链接并收集数据

标签 python web-scraping web-crawler scrapy

我正在尝试在 Scrapy 中编写程序以打开链接并从此标签收集数据:<p class="attrgroup"></p> .

我已经设法让 Scrapy 收集来自给定 URL 的所有链接但不跟随它们。非常感谢任何帮助。

最佳答案

您需要产生 Request链接的实例,分配回调并在回调中提取所需的 p 元素的文本:

# -*- coding: utf-8 -*-
import scrapy


# item class included here 
class DmozItem(scrapy.Item):
    # define the fields for your item here like:
    link = scrapy.Field()
    attr = scrapy.Field()


class DmozSpider(scrapy.Spider):
    name = "dmoz"
    allowed_domains = ["craigslist.org"]
    start_urls = [
    "http://chicago.craigslist.org/search/emd?"
    ]

    BASE_URL = 'http://chicago.craigslist.org/'

    def parse(self, response):
        links = response.xpath('//a[@class="hdrlnk"]/@href').extract()
        for link in links:
            absolute_url = self.BASE_URL + link
            yield scrapy.Request(absolute_url, callback=self.parse_attr)

    def parse_attr(self, response):
        item = DmozItem()
        item["link"] = response.url
        item["attr"] = "".join(response.xpath("//p[@class='attrgroup']//text()").extract())
        return item

关于python - 让 Scrapy 跟随链接并收集数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30152261/

相关文章:

python - 使用 Python 中的 Beautiful Soup 获取 <div> 类 ="some_class"> 标签内 <p> 标签的内容

ajax - shebang/hashbang 有什么用?

python - 正则表达式和 unicode 文字

python - 使用 python selenium 打开多个页面

python - 需要帮助了解 Restful API 中的 SQL 注入(inject)漏洞

python - 访问深层类层次结构中的所有 href 链接

python - 如何从google下载图片并在google-images-download中同时用关键字重命名图片

python - Scrapy View 返回空白页

python - sorl-thumbnail 在 django 中不起作用

python - 使用特定像素边距 numpy opencv 从图像中剪切蒙版