scrapy 零碎的下一页链接

uyto3xhc  于 2022-11-09  发布在  其他
关注(0)|答案(1)|浏览(159)

网站(https://www.bernama.com/en/crime_courts/)对所有分页链接使用相同的类名a=“page-link”。我的目标是获得右侧的下一个按钮,但无法区分上一个按钮、数字按钮和下一个按钮。我当前的代码试图从数组中获得最后一个元素,但失败了。

start_urls = {
    'https://www.bernama.com/en/crime_courts/'
}

def parse(self, response):
    for news in response.css('div.col-7.col-md-12.col-lg-12.mb-3'):
        yield{
            'title' : news.css('a.text-dark.text-decoration-none::text').get(),
            'link' : news.css('a.text-dark.text-decoration-none::attr(href)').get()
        }

    next_page = response.css('a.page-link::attr(href)').getall()

    if next_page[-1] != "#":
        yield response.follow(next_page, callback = self.parse)
pkmbmrz7

pkmbmrz71#

您只是忘记了[-1]

yield response.follow( next_page[-1] )

完整的工作代码,但我使用较短的css选择器
接下来的页面使用相对URL,所以它需要response.urljoin()来创建绝对URL。

import scrapy

class MySpider(scrapy.Spider):

    name = 'my_spyder'

    start_urls = ['https://www.bernama.com/en/crime_courts/']

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

        for news in response.css('h6 a'):
            yield {
                    'title': news.css('::text').get(),
                    'link' : response.urljoin(news.css('::attr(href)').get()),
                    #'link' : response.urljoin(news.attrib['href']),
                    'page' : response.url,
                  }

        next_page = response.css('a.page-link::attr(href)').getall()

        if next_page[-1] != "#":
            yield response.follow(next_page[-1])

from scrapy.crawler import CrawlerProcess

c = CrawlerProcess({
    'USER_AGENT': 'Mozilla/5.0',
    'FEEDS': {'output.csv': {'format': 'csv'}},  # new in 2.1
})
c.crawl(MySpider)
c.start()

顺便说一句:

两个版本的CSS选择器也得到链接到YouTube上的视频,但他们是相同的每一页和CVS有相同的链接很多次。
如果你只需要新闻没有视频,那么它可能需要获得部分,其中有row与文本More news和稍后搜索只在这一部分。

sections = response.xpath('//div[@class="row"]/div[div[@class="row"]//span[contains(text(), "More news")]]')

# print(sections)

for news in sections[0].css('h6 a'):
    yield{
        'title': news.css('::text').get(),
        'link' : response.urljoin(news.css('::attr(href)').get()),
        'page' : response.url,
    }

相关问题