python+scrapy 爬取西刺代理ip(一)


轉自:https://www.cnblogs.com/lyc642983907/p/10739577.html

第一步:環境搭建

1.python2 或 python3

2.用pip安裝下載scrapy框架

具體就自行百度了,主要內容不是在這。

第二步:創建scrapy(簡單介紹)

1.Creating a project(創建項目)

scrapy startproject 項目名稱

2.Defining our item(定義我們的項目)

3.writing a spider(寫spider)

scrapy genspider (spider的名稱)(爬取的網頁)

4.writing & Configure an item Pipeline(編寫和配置項目管道)

5.Execute crawl(執行爬蟲)

scrapy crawl (spider的名稱)

第三步:具體實現

1.創建項目

進入scrapy項目的工作區間(xici項目名)

scrapy startproject xici

此時項目結構是這樣

 

2.創建spider爬蟲

進入項目創建(注意后面的不是具體地址,是域名)

 scrapy genspider xicidaili 'xicidaili.com'

此時,你會發現在spiders文件夾下多了個 xicidaili.py 文件(這就是爬蟲文件)

 

3.編寫items.py

 根據我們的需求編寫

代理ip最主要是ip、端口和類型(http或https)

items.py

復制代碼
# -*- coding: utf-8 -*-

# Define here the models for your scraped items
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/items.html

import scrapy


class XiciItem(scrapy.Item):
    # define the fields for your item here like:
    # name = scrapy.Field()
    ip = scrapy.Field()
    port = scrapy.Field()
    types = scrapy.Field()
復制代碼

4.編寫xicidaili.py

具體爬蟲操作就在這個文件里實現

xicidaili.py

復制代碼
# -*- coding: utf-8 -*-
import scrapy
from xici.items import XiciItem

class XicidailiSpider(scrapy.Spider):
    name = 'xicidaili'
    allowed_domains = ['xicidaili.com']
    #把http://xicidaili.com/地址改為我們需要爬去的具體地址
    start_urls = ['https://www.xicidaili.com/nn/']

    def parse(self, response):
        #我們發現ip都是在table標簽里,那我們就用xpath選擇table元素
        lis = response.xpath('//table[@id="ip_list"]')
        #抓取table下的tr,一個tr就一個ip,端口,類型
        trs = lis[0].xpath('tr')

        items = []
        #除掉第一行
        for ip in trs[1:]:
            item = XiciItem()
            #抓取每一行具體的內容
            # //*[@id="ip_list"]/tbody/tr[2]/td[2]
            item["ip"] = ip.xpath('td[2]/text()')[0].extract()

            # //*[@id="ip_list"]/tbody/tr[2]/td[3]
            item["port"] = ip.xpath('td[3]/text()')[0].extract()

            # //*[@id="ip_list"]/tbody/tr[2]/td[6]
            item["types"] = ip.xpath('td[6]/text()').extract()

            #加入到數組
            items.append(item)
        #返回給items.py
        return items
復制代碼

5.編寫pipelines.py

pipelines文件是對數據進行持久化存儲的 

MySQLdb不支持python3,所以我要用pymysql代替

沒有pymysql需要用pip下載,數據庫表也要自己建

pipelines.py

復制代碼
# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html
import pymysql

class XiciPipeline(object):
    def __init__(self):
        self.client = pymysql.connect(
            host='127.0.0.1',
            port=3306,
            user='root',  # 使用自己的用戶名
            passwd='root',  # 使用自己的密碼
            db='test',  # 數據庫名
            charset='utf8'
        )
        # 拿到游標
        self.cur = self.client.cursor()

    def process_item(self, item, spider):
        #mysql防止sql注入
        sql = ("insert into proxyip(ip,port,types) values (%s,%s,%s)")
        lis = (item['ip'], item['port'], item['types'])
        try:

            self.cur.execute(sql, lis)
            # 向數據庫提交
            self.client.commit()
        except Exception as e:
            print("Insert error:", e)
        #關閉
        self.cur.close()
        return item
復制代碼

6.編寫middlewares.py

middlewares.py中設置用戶代理中間件

對爬蟲進行偽裝,偽裝成人工操作,否則網站會監測出你是爬蟲,並攔截你

 在middlewares.py文件中加入以下代碼:

復制代碼
from scrapy.downloadermiddlewares.useragent import UserAgentMiddleware
import random

#設置代理ip
class MyProxyMiddleware(object):
'''
設置Proxy
'''

def __init__(self, ip):
self.ip = ip

@classmethod
def from_crawler(cls, crawler):
return cls(ip=crawler.settings.get('PROXIES'))

def process_request(self, request, spider):
ip = random.choice(self.ip)
request.meta['proxy'] = ip

class MyUserAgentMiddleware(UserAgentMiddleware):
'''
設置User-Agent
'''

def __init__(self, user_agent):
self.user_agent = user_agent

@classmethod
def from_crawler(cls, crawler):

return cls(
user_agent=crawler.settings.get('USER_AGENTS_LIST')
)

def process_request(self, request, spider):
agent = random.choice(self.user_agent)
request.headers['User-Agent'] = agent
復制代碼

7.編寫settings.py

我們剛才編寫的middlewares.py和pipelines.py都要在settings.py文件里面進行配置,設置優先級等等。

(一定要記得,否則你寫的數據持久化存儲和爬蟲偽裝是沒有生效的,記得把ROBOTSTXT_OBEY改為False)

修改settings.py文件代碼如下:

復制代碼
BOT_NAME = 'xici'

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

#對middlewares編寫的進行配置
DOWNLOADER_MIDDLEWARES = {
    'xici.middlewares.MyProxyMiddleware': 543,
    'scrapy.downloadermiddleware.useragent.UserAgentMiddleware': None,
    'xici.middlewares.MyUserAgentMiddleware': 400,
}

#配置pipelines.py
ITEM_PIPELINES = {
    'xici.pipelines.XiciPipeline': 300
}

#代理的ip
#你看到此篇文章的時候,ip已經沒用了,你可以在西刺網站上拿一個試
PROXIES = ['http://192.168.42.249:808']

#user_agent
USER_AGENTS_LIST = [
    "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",
    "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.11 TaoBrowser/2.0 Safari/536.11",
    "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.71 Safari/537.1 LBBROWSER",
    "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; LBBROWSER)",
    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQDownload 732; .NET4.0C; .NET4.0E; LBBROWSER)",
    "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.84 Safari/535.11 LBBROWSER",
    "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E)",
    "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; QQBrowser/7.0.3698.400)",
    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQDownload 732; .NET4.0C; .NET4.0E)",
    "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; SV1; QQDownload 732; .NET4.0C; .NET4.0E; 360SE)",
    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQDownload 732; .NET4.0C; .NET4.0E)",
    "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E)",
    "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.89 Safari/537.1",
    "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.89 Safari/537.1",
    "Mozilla/5.0 (iPad; U; CPU OS 4_2_1 like Mac OS X; zh-cn) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8C148 Safari/6533.18.5",
    "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:2.0b13pre) Gecko/20110307 Firefox/4.0b13pre",
    "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:16.0) Gecko/20100101 Firefox/16.0",
    "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11",
    "Mozilla/5.0 (X11; U; Linux x86_64; zh-CN; rv:1.9.2.10) Gecko/20100922 Ubuntu/10.10 (maverick) Firefox/3.6.10"
]

# Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = 'xici (+http://www.yourdomain.com)'

#要設置ROBOTSTXT_OBEY改為False
#如果為True,則遵守robots協議(爬蟲協議)

ROBOTSTXT_OBEY = False
復制代碼

8.執行爬蟲

進入項目里面,列出爬蟲

scrapy list

scrapy crawl xicidaili

 

成功爬取

9.問題注意 

1.在執行的時候,可能會卡住,原因是上面用的代理ip已經過期,需要另外找,

或者你可以把ip代理部分去掉,上面示例不用代理ip也能爬取,

找ip代理也是因為你頻繁的訪問,它是禁止了你的ip,沒有也可以不用! 

 2.網站內的html標簽有所改變,我上面xpath已經沒辦法找到我們想要的內容了,需要修改以下xpath


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM