首页 文章

使用Scrapy刮取数据

提问于
浏览
1

我试图用scrapy刮取数据 . 但是在编辑代码时遇到了麻烦 . 以下是我作为实验所做的事情:

import scrapy

class BlogSpider(scrapy.Spider):
    name = 'blogspider'
    start_urls = ['http://anon.example.com/']

    def parse(self, response):
        for title in response.css('h2'):
            yield {'Agent-name': title.css('a ::text').extract_first()}

        next_page = response.css('li.col-md-3 ln-t > div.cs-team team-grid > figure > a ::attr(href)').extract_first()
        if next_page:
            yield scrapy.Request(response.urljoin(next_page), callback=self.parse)

我使用了网站scrapy.org上的示例并尝试修改它 . 此代码正在执行的操作是从给定页面中提取所有代理的名称 .
但是我希望scrapy应该进入代理的页面并从那里提取其信息 .
比如说:

Name: name of the agent
Phone: Phone Number
Email: email address
website: URL of website .. etc

希望这能澄清我的问题 . 我想有一个解决这个问题的方法 .

1 回答

  • 1
    import scrapy
    
    class BlogSpider(scrapy.Spider):
        name = 'blogspider'
        start_urls = ['http://anon.example.com']
    
    
        # get 502 url of name
        def parse(self, response):
            info_urls = response.xpath('//div[@class="text"]//a/@href').extract()
            for info_url in info_urls:
                yield scrapy.Request(url=info_url, callback=self.parse_inof)
        # visit each url and get info
        def parse_inof(self, response):
            info = {}
            info['name'] = response.xpath('//h2/text()').extract_first()
            info['phone'] = response.xpath('//text()[contains(.,"Phone:")]').extract_first()
            info['email'] = response.xpath('//*[@class="cs-user-info"]/li[1]/text()').extract_first()
            info['website'] = response.xpath('//*[@class="cs-user-info"]/li[2]/a/text()').extract_first()
            print(info)
    

    name 可以在详细信息页面中找到,因此在第一步中,我们只收集所有详细信息网址 .

    然后我们访问所有网址并获取所有信息 .

    日期可能需要清理,但想法很清楚 .

相关问题