0

Webscraping 一个色情网站,我正在制作一个蜘蛛,它在分页中爬行以获取最新视频,为每页 32 个视频中的每一个抓取元数据。

接下来是我的蜘蛛代码:

class NaughtySpider(scrapy.Spider):
  name = "naughtyspider"
  allowed_domains = ["pornhub.com"]
  max_pages = 3
  # Start request
  def start_requests(self):
        for i in range(1, self.max_pages):
            yield scrapy.Request('https://www.pornhub.com/video?o=cm&page=%s' % i, callback=self.parse_video)
  # First parsing method
  def parse_video(self, response):
    self.log('F i n i s h e d  s c r a p i n g ' + response.url)
    video_links = response.css('ul#videoCategory').css('li.videoBox').css('div.thumbnail-info-wrapper').css('span.title > a').css('::attr(href)') #Correct path, chooses 32 videos from page ignoring the links coming from ads
    links_to_follow = video_links.extract()
    for url in links_to_follow:
      yield response.follow(url = url,
                            callback = self.parse_metadata)
  # Second parsing method
  def parse_metadata(self, response):
    # Create a SelectorList of the course titles text
    video_title = response.css('div.title-container > h1.title > span.inlineFree::text')
    # Extract the text and strip it clean
    video_title_ext = video_title.extract_first()
    # Extract views
    video_views = response.css('span.count::text').extract_first()
    # Extract tags
    video_tags = response.css('div.tagsWrapper a::text').extract()
    # Extract Categories
    video_categories = response.css('div.categoriesWrapper a::text').extract()
    # Fill in the dictionary
    yield {
        'title': video_title_ext,
        'views': video_views,
        'tags': video_tags,
        'categories': video_categories,
    }

问题是几乎一半的条目最终都是空的,没有标题、视图、标签或类别。日志示例:

[scrapy.core.scraper] DEBUG: Scraped from <200 https://www.pornhub.com/view_video.php?viewkey=ph5d594b093f8d6>
{'title': None, 'views': None, 'tags': [], 'categories': []}

但同时,如果我在scrapy shell中获取相同的链接,并在蜘蛛中复制并粘贴相同的选择器路径,它会给我正确的值:

In [4]: fetch('https://www.pornhub.com/view_video.php?viewkey=ph5d594b093f8d6')
[scrapy.core.engine] DEBUG: Crawled (200) <GET https://www.pornhub.com/view_video.php?viewkey=ph5d594b093f8d6> (referer: None)

In [5]: response.css('div.tagsWrapper a::text').extract()
Out[5]: ['alday', '559', '+ ']

In [6]: response.css('span.count::text').extract_first()
Out[6]: '6'

提前感谢您的帮助。

编辑:我认为这不是我的代码问题而是对服务器的限制以避免被刮掉,我是否正确?

4

1 回答 1

0

视图、持续时间等数据似乎是由 HTML 变量元素调用的<var> DATA </var>。例如,如果你在你的 scrapy shell 中输入以下行,你应该得到视图。

response.xpath(".//var[@class='duration')")

不确定它是否会起作用,但值得一试。

Ps 我得告诉我妻子这是为了教育目的..

于 2019-08-18T18:30:13.070 回答