scrapy從安裝到爬取煎蛋網圖片

下載地址:https://www.lfd.uci.edu/~gohlke/pythonlibs/
pip install wheel
pip install lxml
pip install pyopenssl
pip install Twisted
pip install pywin32
pip install scrapy

scrapy startproject jandan 創建項目
cd?jandan
cd?jandan

items.py 存放數據
pipelines.py 管道文件

?

由于煎蛋網有反爬蟲措施,我們需要做一些處理

settings文件

ROBOTSTXT_OBEY = False #不遵尋reboot協議
DOWNLOAD_DELAY = 2 #下載延遲時間
DOWNLOAD_TIMEOUT = 15 #下載超時時間
COOKIES_ENABLED = False #禁用cookie

DOWNLOADER_MIDDLEWARES = {
#請求頭
'jandan.middlewares.RandomUserAgent': 100,
#代理ip
'jandan.middlewares.RandomProxy': 200,
}
#請求列表
USER_AGENTS = [
#遨游
"Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Maxthon 2.0)",
#火狐
"Mozilla/5.0 (Windows NT 6.1; rv:2.0.1) Gecko/20100101 Firefox/4.0.1",
#谷歌
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_0) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11"
]

#代理ip列表
PROXIES = [
{"ip_port":"119.177.90.103:9999","user_passwd":""},
#代理ip無密碼
{"ip_port":"101.132.122.230:3128","user_passwd":""},
#代理ip有密碼
# {"ip_port":"123.139.56.238:9999","user_passwd":"root:admin"}
]
#管道文件,取消注釋
ITEM_PIPELINES = {
'jandan.pipelines.JandanPipeline': 300,
}
IMAGES_STORE = "images"

?

middlewares文件
import random
import base64
from jandan.settings import USER_AGENTS
from jandan.settings import PROXIESclass RandomUserAgent(object):def process_request(self,request,spider):useragent = random.choice(USER_AGENTS)request.headers.setdefault("User-Agent",useragent)class RandomProxy(object):def process_request(self,request,spider):proxy = random.choice(PROXIES)if proxy["user_passwd"] is None:request.meta["proxy"] = "http://" + proxy["ip_port"]else:# b64編碼接收字節對象,在py3中str是unicode,需要轉換,返回是字節對象base64_userpasswd = base64.b16encode(proxy["user_passwd"].encode())request.meta["proxy"] = "http://" + proxy["ip_port"]#拼接是字符串,需要轉碼request.headers["Proxy-Authorization"] = "Basic " + base64_userpasswd.decode()

?

?

items文件

import scrapyclass JandanItem(scrapy.Item):name = scrapy.Field()url = scrapy.Field()

?

scrapy genspider ?-t crawl dj jandan.net 創建crawlscrapy類爬蟲
會自動在spiders下創建jandan.py文件,頁面由js編寫,需要BeautifulSoup類定位js元素獲取數據

# -*- coding: utf-8 -*-
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from jandan.items import JandanItem
from selenium import webdriver
from bs4 import BeautifulSoup as bs4class JdSpider(CrawlSpider):name = 'jd'allowed_domains = ['jandan.net']start_urls = ['http://jandan.net/pic/page-1#comments/']rules = (Rule(LinkExtractor(allow=r'pic/page-\d+'), callback='parse_item', follow=True),)def parse_item(self, response):item = JandanItem()driver = webdriver.PhantomJS()driver.get(response.url)soup = bs4(driver.page_source, 'html.parser')all_data = soup.find_all('div', {'class': 'row'})for i in all_data:name = i.find("strong")item["name"] = name.get_text().strip()link = i.find('a', {'class': 'view_img_link'})url = link.get("href")if len(url) == 0:returnitem["url"] = "http://" + url.split("//")[-1]yield item

?

pipelines.py

import json
import os
import requests
from scrapy.conf import settingsclass JandanPipeline(object):
   #保存為json文件
# def __init__(self):# self.filename = open("jandan.json","wb")# self.num = 0# # def process_item(self, item, spider):# text = json.dumps(dict(item),ensure_ascii=False) + "\n"# self.filename.write(text.encode("utf-8"))# self.num += 1# return item# # def close_spider(self,spider):# self.filename.close()# print("總共有" + str(self.num) + "個資源")
  #下載到本地def process_item(self, item, spider):if 'url' in item:dir_path = settings["IMAGES_STORE"]if not os.path.exists(dir_path):os.makedirs(dir_path)su = "." + item["url"].split(".")[-1]path = item["name"] + sunew_path = '%s/%s' % (dir_path, path)if not os.path.exists(new_path):with open(new_path, 'wb') as handle:response = requests.get(item["url"], stream=True)for block in response.iter_content(1024):if not block:breakhandle.write(block)return item

?

?


scrapy crawl dj 啟動爬蟲


scrapy shell "https://hr.tencent.com/position.php?&start=0" 發送請求

?

?奉上我的github地址,會定期更新項目

https://github.com/bjptw/workspace

?

轉載于:https://www.cnblogs.com/bjp9528/p/9318013.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/389128.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/389128.shtml
英文地址,請注明出處:http://en.pswp.cn/news/389128.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

高斯金字塔 拉普拉斯金字塔_金字塔學入門指南

高斯金字塔 拉普拉斯金字塔The topic for today is on data validation and settings management using Python type hinting. We are going to use a Python package called pydantic which enforces type hints at runtime. It provides user-friendly errors, allowing you …

基本排序算法

插入排序 基本思想&#xff1a;把待排序列表分為已排和未排序兩部分&#xff0c;從未排序左邊取值&#xff0c;按順序從已排序的右端開始對比插入到相應的位置。 java代碼實現 private void insertSort(int[] arr){int i, j;int temp;for(i 0; i < arr.length; i){temp …

自定義版本更新彈窗

目錄介紹 1.Animation和Animator區別 2.Animation運行原理和源碼分析 2.1 基本屬性介紹2.2 如何計算動畫數據2.3 什么是動畫更新函數2.4 動畫數據如何存儲2.5 Animation的調用 3.Animator運行原理和源碼分析 3.1 屬性動畫的基本屬性3.2 屬性動畫新的概念3.3 PropertyValuesHold…

《SQL Server 2008從入門到精通》--20180716

1.鎖 當多個用戶同時對同一個數據進行修改時會產生并發問題&#xff0c;使用事務就可以解決這個問題。但是為了防止其他用戶修改另一個還沒完成的事務中的數據&#xff0c;就需要在事務中用到鎖。 SQL Server 2008提供了多種鎖模式&#xff1a;排他鎖&#xff0c;共享鎖&#x…

googleearthpro打開沒有地球_嫦娥五號成功著陸地球!為何嫦娥五號返回時會燃燒,升空卻不會?...

目前&#xff0c;嫦娥五號已經帶著月壤成功降落到地球上&#xff0c;創造了中國航天的又一里程碑。嫦娥五號這一路走來&#xff0c;困難重重&#xff0c;但都被我國航天科技人員逐一克服&#xff0c;最終圓滿地完成了嫦娥五號的月球采樣返回地球任務。嫦娥五號最后這一步走得可…

語言認知偏差_我們的認知偏差正在破壞患者的結果數據

語言認知偏差How do we know if we are providing high-quality care? The answer to this question is sought by a multitude of parties: patients, clinicians, educators, legislators, and insurance companies. Unfortunately, it’s not easy to determine. There is …

android 打包相關問題記錄

Android 中的打包配置在build.gradle文件中&#xff0c;下面對該文件的內容做一下記錄。 buildscript {repositories {jcenter()}dependencies {classpath com.android.tools.build:gradle:2.2.0} } 這里生命了倉庫的位置&#xff0c;依賴gradle的版本。 android{} android {…

本文將引導你使用XNA Game Studio Express一步一步地創建一個簡單的游戲

本文將引導你使用XNA Game Studio Express一步一步地創建一個簡單的游戲 第1步: 安裝軟件 第2步: 創建新項目 第3步: 查看代碼 第4步: 加入一個精靈 第5步: 使精靈可以移動和彈跳 第6步: 繼續嘗試! 完整的實例 第1步: 安裝軟件在動手之前,先確定你已經安裝了所需的軟件,其中包…

C#中實現對象的深拷貝

深度拷貝指的是將一個引用類型&#xff08;包含該類型里的引用類型&#xff09;拷貝一份(在內存中完完全全是兩個對象&#xff0c;沒有任何引用關系)..........  直接上代碼&#xff1a; 1 /// <summary>2 /// 對象的深度拷貝&#xff08;序列化的方式&#xf…

Okhttp 源碼解析

HTTP及okhttp的優勢 http結構 請求頭 列表內容表明本次請求的客戶端本次請求的cookie本次請求希望返回的數據類型本次請求是否采用數據壓縮等等一系列設置 請求體 指定本次請求所使用的方法請求所使用的方法 響應頭 - 服務器標識 - 狀態碼 - 內容編碼 - cookie 返回給客…

python中定義數據結構_Python中的數據結構。

python中定義數據結構I remembered the day when I made up my mind to learn python then the very first things I learned about data types and data structures. So in this article, I would like to discuss different data structures in python.我記得當初下定決心學習…

python實訓英文_GitHub - MiracleYoung/You-are-Pythonista: 匯聚【Python應用】【Python實訓】【Python技術分享】等等...

You-are-Pythonista匯聚【從零單排】【實戰項目】【數據科學】【自然語言處理】【計算機視覺】【面試題系列】【大航海】【Python應用】【錯題集】【技術沙龍】【內推渠道】等等【人人都是Pythonista】由公眾號【Python專欄】推出&#xff0c;請認準唯一標識&#xff1a;請仔細…

java電子商務系統源碼 Spring MVC+mybatis+spring cloud+spring boot+spring security

鴻鵠云商大型企業分布式互聯網電子商務平臺&#xff0c;推出PC微信APP云服務的云商平臺系統&#xff0c;其中包括B2B、B2C、C2C、O2O、新零售、直播電商等子平臺。 分布式、微服務、云架構電子商務平臺 java b2b2c o2o 技術解決方案 開發語言&#xff1a; java、j2ee 數據庫&am…

Go語言實現FastDFS分布式存儲系統WebAPI網關

前言 工作需要&#xff0c;第一次使用 Go 來實戰項目。 需求&#xff1a;采用 golang 實現一個 webapi 的中轉網關&#xff0c;將一些資源文件通過 http 協議上傳至 FastDFS 分布式文件存儲系統。 一、FastDFS 與 golang 對接的代碼 github&#xff1a;https://github.com/weil…

builder 模式

首先提出幾個問題&#xff1a; 什么是Builder模式&#xff1f;為什么要使用Builder模式&#xff1f;它的優點是什么&#xff0c;那缺點呢&#xff1f;什么情況下使用Builder模式&#xff1f; 關于Builder模式在代碼中用的很多&#xff0c;比如AlertDialog, OkHttpClient等。一…

工作失職的處理決定_工作失職的處理決定

精品文檔2016全新精品資料-全新公文范文-全程指導寫作–獨家原創1/3工作失職的處理決定失職是指工作人員對本職工作不認真負責&#xff0c;未依照規定履行自己的職務&#xff0c;致使單位或服務對象造成損失的行為。關于工作失職的處理決定該怎么寫呢?下面學習啦小編給大家帶來…

venn diagram_Venn Diagram Python軟件包:Vennfig

venn diagram目錄 (Table of Contents) Introduction 介紹 Installation 安裝 Default Functions 默認功能 Parameters 參量 Examples 例子 Conclusion 結論 介紹 (Introduction) In the last article, I showed how to draw basic Venn diagrams using matplotlib_venn.在上一…

應用程序的主入口點應用程序的主入口點應用程序的主入口點

/// <summary>/// 應用程序的主入口點。/// </summary>[STAThread]static void Main(string[] args){Stream stream Assembly.GetExecutingAssembly().GetManifestResourceStream("CapApp.TestApp.exe");byte[] bs new byte[stream.Length];stream.Rea…

創夢天地通過聆訊:上半年經營利潤1.3億 騰訊持股超20%

雷帝網 雷建平 11月23日報道時隔半年后&#xff0c;樂逗游戲母公司創夢天地終于通過上市聆訊&#xff0c;這意味著創夢天地很快將在港交所上市。創夢天地聯合保薦人包括瑞信、招商證券國際、中金公司。當前&#xff0c;創夢天地運營的游戲包括《夢幻花園》、《快樂點點消》、《…

PyCharm之python書寫規范--消去提示波浪線

強迫癥患者面對PyCharm的波浪線是很難受的&#xff0c;針對如下代碼去除PyCharm中的波浪線&#xff1a; # _*_coding:utf-8_*_ # /usr/bin/env python3 A_user "lin" A_password "lin123"for i in range(3): # 循環次數為3name input("請輸入你的…