【问题标题】:How to get details page and follow the links with Scrapy?如何获取详细信息页面并使用 Scrapy 访问链接?
【发布时间】:2018-07-12 08:16:40
【问题描述】:

我有问题。我想抓取一个成人故事网站。而且我有很多网站要抓取。例如,我想抓取 2 个网站,如下所示:

import scrapy
from scrapy.selector import HtmlXPathSelector
from scrapy.selector import Selector
from scrapy.http import HtmlResponse

class Cerita(scrapy.Spider):
   name = "cerita"
   allowed_domains = [
      "ceritabokep.me",
      "ceritangewe.com"
   ]

   start_urls = [
       'http://ceritabokep.me/',
       'https://ceritangewe.com'
   ]

   def parse(self, response):
      divs = response.xpath('//div')
      for p in divs.xpath('.//p'):
        yield {
            'content': p.extract(),
            'url': response.request.url
        }

    next_page = response.css('a::attr(href)')
    if next_page is not None:
        for href in response.css('a'):
            yield response.follow(href, callback=self.parse)

我只想在每个页面网站中获取段落或文本。但是当我运行蜘蛛时,蜘蛛只会抓取主页中的亮点,而不是直到详细信息页面。如下:

[
{"content": "<p itemprop=\"description\" class=\"post_excerpt\">Seperi biasa 
akhir pekan semua terlihat santai tidak melakukan aktivitas tapi seperti 
biasa ibuku menghadiri arisan ibu berpesan untuk menjaga rumah,\nibu : 
\u201cJovita, ibu mau arisan di antar sama adik, kamu jaga rumah 
ya\u201d\naku : \u201cia ibu ku sayang, Jovita dirumah aja kok\u201d  \u00a0  
ibu : \u201cooo...</p>", "url": "http://ceritabokep.me/"},
{"content": "<p itemprop=\"description\" class=\"post_excerpt\">Aku kerja 
sebagai trainer berenang disatu sport hall yang berada di kawasan prumahan 
elit yang mayoritas penghuninya warga keturunan. Perumahannya mewah, rumahnya 
gak banyak tapi besar-besar. Sport Hallnya lengkap,lapangan tenis, gym,kolam 
renang,malah disediakan juga lapangan basket merangkap volley dan bulu 
tangkis.kalo peralatan untuk tenis meja...</p>", "url": 
"http://ceritabokep.me/"},
]

它已断开连接,因为链接 阅读更多 我想爬取网站上的所有页面,如何跟踪所有页面链接并获取详细信息页面?因为每个网站都有不同的元素。

【问题讨论】:

    标签: python python-3.x scrapy web-crawler scrapy-spider


    【解决方案1】:

    您想爬取发现多个域中的文章 url,为此您需要为每个网站构建一个案例或使用一些可以确定哪些 url 是文章的智能算法。

    如果您只有几个网站(例如示例中的网站),那么最简单的方法就是在案例中编写代码:

    def parse(self, response): 
        # css selector for domain #1
        articles = response.css('h5 a::attr(href)').extract()
        if not articles:
            # if nothing found use css selector for domain #2
            articles = response.css('h2 a::attr(href)').extract()
    

    或者以您的示例为例,您可以看到所有文章在两个域的 url 中都有 /cerita

    def parse(self, response): 
        # css selector for domain #1
        urls = response.css('a::attr(href)').extract()
        articles = [url for url in urls if '/cerita' in url]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-23
      • 1970-01-01
      相关资源
      最近更新 更多