在scrapy中逐个选择结果

2024-10-16 22:35:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我从Indeed下载了一个页面的源代码,并试图从中获取所有的职位,为此,我使用以下xpath:

response.xpath('//*[@class="  row  result"]//*[@class="jobtitle"]//text()').extract()

问题是结果不在一行,因此得到的结果是:

^{pr2}$

第一个要提取的数据有问题吗

response.xpath('//*[@class="  row  result"]').extract_first()

但是对于任何给定的索引,并且可以选择继续处理数据。 我试过了:

current_job = response.xpath('//*[@class="  row  result"]').extract_first()
current_job = TextResponse(url='',body=current_job,encoding='utf-8') 

但它只适用于第一个结果,对我来说这不像一个Python式的方法。在


Tags: 数据源代码response职位jobextract页面result
2条回答

试试看。你需要稍微修改一下我的脚本以适合你的项目。你可以解决上面提到的问题。在

import requests
from scrapy import Selector

res = requests.get("https://www.indeed.cl/trabajo?q=Data%20scientist")
sel = Selector(res)
for item in sel.css("h2.jobtitle a"):
    title = ' '.join(item.css("::text").extract())
    print(title)

输出:

^{pr2}$

首先,我只得到a(没有text()extract()),然后我将使用fortext()和{}与everya分开使用,而join()将元素连接到带标题的字符串中。在

import scrapy

class MySpider(scrapy.Spider):

    name = 'myspider'

    start_urls = ['https://www.indeed.cl/trabajo?q=Data%20scientist&l=']

    def parse(self, response):
        print('url:', response.url)

        results = response.xpath('//h2[@class="jobtitle"]/a')
        print('number:', len(results))

        for item in results:
            title = ''.join(item.xpath('.//text()').extract())
            print('title:', title)

#  - it runs without project and saves in `output.csv`  -

from scrapy.crawler import CrawlerProcess

c = CrawlerProcess({
    'USER_AGENT': 'Mozilla/5.0',
})
c.crawl(MySpider)
c.start()

结果:

^{pr2}$

相关问题 更多 >