吾爱破解 - 52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 3472|回复: 13
收起左侧

[求助] python的scrapy框架爬取Boos直聘无果,被封ip了

[复制链接]
lyz88588 发表于 2020-10-30 11:57
新手学习爬虫进入困境咯。。。



第一,创建items:
[Python] 纯文本查看 复制代码
class BoosItem(scrapy.Item):
    # define the fields for your item here like:
    title_name = scrapy.Field(serializer=str) # 岗位名称
    company_name = scrapy.Field(serializer=str) # 公司名称
    job_limit = scrapy.Field(serializer=str) # 薪资
    job_desc = scrapy.Field(serializer=str) # 工作详情
    pass



第二编写BoosSpider
[Python] 纯文本查看 复制代码
class BoosSpider(scrapy.Spider):
    name = 'Boos'
    # allowed_domains = ['www.zhipin.com']
    start_urls = ['https://www.zhipin.com/c101120100/?query=python&page=1']
    # base_url = 'https://www.zhipin.com'

    # 回调函数接受item
    def parse_detail(self,response):
        item = response.meta['item']
        item['job_desc'] = response.xpath('//*[@id="main"]/div[3]/div/div[2]/div[2]/div[1]/div/text()').extract()
        yield item

    def parse(self, response):
        # print(response)
        li_list = response.xpath('//div[@class="job-list"]/ul/li')
        # print(li_list)
        for li in li_list:
            item = BoosItem()
            item['title_name'] =  li.xpath('./div/div[1]/div[1]/div/div[1]/span[1]/a/text()').extract_first()
            item['company_name'] =li.xpath('./div/div[1]/div[2]/div/h3/a/text()').extract_first()
            item['job_limit'] =li.xpath('./div/div[1]/div[1]/div/div[2]/span/text()').extract_first()
            # 对详情页发请求获取详情页的页面源码数据
            # 手动请求的发送
            # 请求传参:meta={},可以将meta字典传递给请求对应的回调函数
            details_url = 'https://www.zhipin.com'+li.xpath('./div/div[1]/div[1]/div/@href').extract_first()
            yield scrapy.Request(details_url,callback=self.parse_detail,meta={'item':item})



在这里就出现问题 了,正常的是返回一个空列表返回一个空数据,我返回了一下response,发现是错误的页面,所以导致无法获取


第三,编写中间件:
[Python] 纯文本查看 复制代码
# Define here the models for your spider middleware
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/spider-middleware.html

from scrapy import signals
from selenium import webdriver
import random
import time
from scrapy.http.response.html import HtmlResponse
from selenium.webdriver.chrome.options import Options # 引入无头

# useful for handling different item types with a single interface
from itemadapter import is_item, ItemAdapter

class CookiesMiddlewares(object):
    USER_AGENTS = [
        "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; AcooBrowser; .NET CLR 1.1.4322; .NET CLR 2.0.50727)",
        "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; Acoo Browser; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 3.0.04506)",
        "Mozilla/4.0 (compatible; MSIE 7.0; AOL 9.5; AOLBuild 4337.35; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)",
        "Mozilla/5.0 (Windows; U; MSIE 9.0; Windows NT 9.0; en-US)",
        "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET CLR 2.0.50727; Media Center PC 6.0)",
        "Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET CLR 1.0.3705; .NET CLR 1.1.4322)",
        "Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 5.2; .NET CLR 1.1.4322; .NET CLR 2.0.50727; InfoPath.2; .NET CLR 3.0.04506.30)",
        "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN) AppleWebKit/523.15 (KHTML, like Gecko, Safari/419.3) Arora/0.3 (Change: 287 c9dfb30)",
        "Mozilla/5.0 (X11; U; Linux; en-US) AppleWebKit/527+ (KHTML, like Gecko, Safari/419.3) Arora/0.6",
        "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.2pre) Gecko/20070215 K-Ninja/2.1.1",
        "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9) Gecko/20080705 Firefox/3.0 Kapiko/3.0",
        "Mozilla/5.0 (X11; Linux i686; U;) Gecko/20070322 Kazehakase/0.4.5",
        "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.8) Gecko Fedora/1.9.0.8-1.fc10 Kazehakase/0.5.6",
        "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11",
        "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_3) AppleWebKit/535.20 (KHTML, like Gecko) Chrome/19.0.1036.7 Safari/535.20",
        "Opera/9.80 (Macintosh; Intel Mac OS X 10.6.8; U; fr) Presto/2.9.168 Version/11.52",
    ]
    def __init__(self):
        print("初始化浏览器")
        # 创建一个无头对象,用来控制谷歌浏览器无界面模式打开
        # chrome_options = Options()
        # chrome_options.add_argument('--headless')
        # chrome_options.add_argument('--disable-gpu')chrome_options=chrome_options
        self.driver = webdriver.Chrome()

    def process_request(self,request,spider):
        user_agent =  random.choice(self.USER_AGENTS)
        request.headers['User-Agents'] = user_agent
        self.driver.get(request.url)
        time.sleep(5)
        # 我们等待5秒钟,让其加载
        source = self.driver.page_source
        #获取页面的源码
        response = HtmlResponse(url=self.driver.current_url,body=source,request=request,encoding='utf-8')
        # Response 对象用来描述一个HTTP响应
        return response
        # 这样我们就获取到了所有的信息,并返回response




到这里我使用了selenium打开网页,在进行获取,可以打开相关网页,可以跳转详情页获取,但是还没有获取完毕,就被封IP了




第四,
[Java] 纯文本查看 复制代码
class BoosPipeline:
    def process_item(self, item, spider):
        print(item)
        return item




这里想看看item输出,现在连输出都没有,就被封了


第五
[Python] 纯文本查看 复制代码
# Scrapy settings for boos project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
#     https://docs.scrapy.org/en/latest/topics/settings.html
#     https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
#     https://docs.scrapy.org/en/latest/topics/spider-middleware.html

BOT_NAME = 'boos'

SPIDER_MODULES = ['boos.spiders']
NEWSPIDER_MODULE = 'boos.spiders'

LOG_LEVEL = 'ERROR'

# Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = 'boos (+http://www.yourdomain.com)'
USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_3) AppleWebKit/535.20 (KHTML, like Gecko) Chrome/19.0.1036.7 Safari/535.20' #伪装请求载体身份



# Obey robots.txt rules
ROBOTSTXT_OBEY = False

# Configure maximum concurrent requests performed by Scrapy (default: 16)
#CONCURRENT_REQUESTS = 32

# Configure a delay for requests for the same website (default: 0)
# See https://docs.scrapy.org/en/latest/topics/settings.html#download-delay
# See also autothrottle settings and docs
DOWNLOAD_DELAY = 3 # 开启下载延迟
# The download delay setting will honor only one of:
#CONCURRENT_REQUESTS_PER_DOMAIN = 16
#CONCURRENT_REQUESTS_PER_IP = 16

# Disable cookies (enabled by default)
# COOKIES_ENABLED = False

# Disable Telnet Console (enabled by default)
#TELNETCONSOLE_ENABLED = False

# Override the default request headers:
#DEFAULT_REQUEST_HEADERS = {
#   'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
#   'Accept-Language': 'en',
#}

# Enable or disable spider middlewares
# See https://docs.scrapy.org/en/latest/topics/spider-middleware.html
#SPIDER_MIDDLEWARES = {
#    'boos.middlewares.BoosSpiderMiddleware': 543,
#}

# Enable or disable downloader middlewares
# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
DOWNLOADER_MIDDLEWARES = {
   'boos.middlewares.CookiesMiddlewares': 100,
}

# Enable or disable extensions
# See https://docs.scrapy.org/en/latest/topics/extensions.html
#EXTENSIONS = {
#    'scrapy.extensions.telnet.TelnetConsole': None,
#}

# Configure item pipelines
# See https://docs.scrapy.org/en/latest/topics/item-pipeline.html
ITEM_PIPELINES = {
   'boos.pipelines.BoosPipeline': 300,
   # 'boos.pipelines.MySqlPipeline': 301,
}

# Enable and configure the AutoThrottle extension (disabled by default)
# See https://docs.scrapy.org/en/latest/topics/autothrottle.html
#AUTOTHROTTLE_ENABLED = True
# The initial download delay
#AUTOTHROTTLE_START_DELAY = 5
# The maximum download delay to be set in case of high latencies
#AUTOTHROTTLE_MAX_DELAY = 60
# The average number of requests Scrapy should be sending in parallel to
# each remote server
#AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0
# Enable showing throttling stats for every response received:
#AUTOTHROTTLE_DEBUG = False

# Enable and configure HTTP caching (disabled by default)
# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings
#HTTPCACHE_ENABLED = True
#HTTPCACHE_EXPIRATION_SECS = 0
#HTTPCACHE_DIR = 'httpcache'
#HTTPCACHE_IGNORE_HTTP_CODES = []
#HTTPCACHE_STORAGE = 'scrapy.extensions.httpcache.FilesystemCacheStorage'




求助各位大佬,怎么办。小白的我不知道怎么进行写了,求帮帮

发帖前要善用论坛搜索功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

chinaqin 发表于 2020-10-30 12:02
用个ip代{过}{滤}理啊 ,我就是在网上用的ip代{过}{滤}理
gongsui 发表于 2020-10-30 12:04
我连框架都还没学,就已经为ip问题头疼了,基本上大网站都会封ip的,所以,没有ip感觉无法进入下一步学习。
imyxuan 发表于 2020-10-30 12:11
gongsui 发表于 2020-10-30 12:04
我连框架都还没学,就已经为ip问题头疼了,基本上大网站都会封ip的,所以,没有ip感觉无法进入下一步学习。

用IP池,或者sleep一下,不要太频繁
choujie1689 发表于 2020-10-30 12:13
加个延时靠谱一点,之前我怕前程无忧,现在也爬不到了,哈哈
弗由 发表于 2020-10-30 12:39
硬核分享。
xxoopp 发表于 2020-10-30 12:55
BOSS是真的狗,你正常浏览多刷几次都告诉你今天不能访问了
头像被屏蔽
枫子树 发表于 2020-10-30 14:57
提示: 作者被禁止或删除 内容自动屏蔽
 楼主| lyz88588 发表于 2020-10-30 23:09
chinaqin 发表于 2020-10-30 12:02
用个ip代{过}{滤}理啊 ,我就是在网上用的ip代{过}{滤}理

这个,有时间我尝试一下。
 楼主| lyz88588 发表于 2020-10-30 23:11
枫子树 发表于 2020-10-30 14:57
花钱买ip  构建代{过}{滤}理池

那个,我在刚开始抓取元素的时候,response会访问一个报错的页面,抓取不到列表元素。这个是什么问题呢?
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则

返回列表

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - LCG - LSG ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2024-11-26 11:45

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表