最近中文字幕2019高清,亚洲人成高清在线播放,男生淦哭男生图片动漫有字,国产亚洲精品九九久在线观看,无码av专区丝袜专区

Python代理IP爬蟲(chóng)的菜鳥(niǎo)使用教程

優(yōu)采云 發(fā)布時(shí)間: 2020-06-24 08:01

  前言

  Python爬蟲(chóng)要經(jīng)歷爬蟲(chóng)、爬蟲(chóng)被限制、爬蟲(chóng)反限制的過(guò)程。當然后續還要網(wǎng)頁(yè)爬蟲(chóng)限制優(yōu)化爬蟲(chóng)代理,爬蟲(chóng)再反限制的一系列道高一尺魔高一丈的過(guò)程。爬蟲(chóng)的中級階段,添加headers和ip代理可以解決好多問(wèn)題。

  本人自己在爬取豆瓣讀書(shū)的時(shí)侯,就以為爬取次數過(guò)多,直接被封了IP.后來(lái)就研究了代理IP的問(wèn)題.

  (當時(shí)不知道哪些情況,差點(diǎn)態(tài)度就崩了...),下面給你們介紹一下我自己代理IP爬取數據的問(wèn)題,請你們強調不足之處.

  問(wèn)題

  這是我的IP被封了,一開(kāi)始好好的,我還以為是我的代碼問(wèn)題了

  

  思路:

  從網(wǎng)上查找了一些關(guān)于爬蟲(chóng)代理IP的資料,得到下邊的思路

  爬取一些IP,過(guò)濾掉不可用. 在requests的懇求的proxies參數加入對應的IP. 繼續爬取. 收工 好吧,都是屁話(huà),理論你們都懂,上面直接上代碼...

  思路有了,動(dòng)手上去.

  運行環(huán)境

  Python 3.7, Pycharm

  這些須要你們直接去搭建好環(huán)境...

  準備工作

  爬取IP地址的網(wǎng)站(國內高匿代理) 校準IP地址的網(wǎng)站 你之前被封IP的py爬蟲(chóng)腳本...

  上面的網(wǎng)址看個(gè)人的情況來(lái)選定

  爬取IP的完整代碼

  PS:簡(jiǎn)單的使用bs4獲取IP和端口號,沒(méi)有啥難度,里面降低了一個(gè)過(guò)濾不可用IP的邏輯

  關(guān)鍵地方都有注釋了

  

#!/usr/bin/env python3

# -*- coding: utf-8 -*-

# @Time : 2018/11/22

# @Author : liangk

# @Site :

# @File : auto_archive_ios.py

# @Software: PyCharm

import requests

from bs4 import BeautifulSoup

import json

class GetIp(object):

"""抓取代理IP"""

def __init__(self):

"""初始化變量"""

self.url = 'http://www.xicidaili.com/nn/'

self.check_url = 'https://www.ip.cn/'

self.ip_list = []

@staticmethod

def get_html(url):

"""請求html頁(yè)面信息"""

header = {

'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36'

}

try:

request = requests.get(url=url, headers=header)

request.encoding = 'utf-8'

html = request.text

return html

except Exception as e:

return ''

def get_available_ip(self, ip_address, ip_port):

"""檢測IP地址是否可用"""

header = {

'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36'

}

ip_url_next = '://' + ip_address + ':' + ip_port

proxies = {'http': 'http' + ip_url_next, 'https': 'https' + ip_url_next}

try:

r = requests.get(self.check_url, headers=header, proxies=proxies, timeout=3)

html = r.text

except:

print('fail-%s' % ip_address)

else:

print('success-%s' % ip_address)

soup = BeautifulSoup(html, 'lxml')

div = soup.find(class_='well')

if div:

print(div.text)

ip_info = {'address': ip_address, 'port': ip_port}

self.ip_list.append(ip_info)

def main(self):

"""主方法"""

web_html = self.get_html(self.url)

soup = BeautifulSoup(web_html, 'lxml')

ip_list = soup.find(id='ip_list').find_all('tr')

for ip_info in ip_list:

td_list = ip_info.find_all('td')

if len(td_list) > 0:

ip_address = td_list[1].text

ip_port = td_list[2].text

# 檢測IP地址是否有效

self.get_available_ip(ip_address, ip_port)

# 寫(xiě)入有效文件

with open('ip.txt', 'w') as file:

json.dump(self.ip_list, file)

print(self.ip_list)

# 程序主入口

if __name__ == '__main__':

get_ip = GetIp()

get_ip.main()

  使用方式完整代碼

  PS: 主要是通過(guò)使用隨機的IP來(lái)爬取,根據request_status來(lái)判定這個(gè)IP是否可以用.

  為什么要這樣判定?

  主要是即使前面經(jīng)過(guò)了過(guò)濾,但是不代表在你爬取的時(shí)侯是可以用的,所以還是得多做一個(gè)判定.

  

#!/usr/bin/env python3

# -*- coding: utf-8 -*-

# @Time : 2018/11/22

# @Author : liangk

# @Site :

# @File : get_douban_books.py

# @Software: PyCharm

from bs4 import BeautifulSoup

import datetime

import requests

import json

import random

ip_random = -1

article_tag_list = []

article_type_list = []

def get_html(url):

header = {

'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36'

}

global ip_random

ip_rand, proxies = get_proxie(ip_random)

print(proxies)

try:

request = requests.get(url=url, headers=header, proxies=proxies, timeout=3)

except:

request_status = 500

else:

request_status = request.status_code

print(request_status)

while request_status != 200:

ip_random = -1

ip_rand, proxies = get_proxie(ip_random)

print(proxies)

try:

request = requests.get(url=url, headers=header, proxies=proxies, timeout=3)

except:

request_status = 500

else:

request_status = request.status_code

print(request_status)

ip_random = ip_rand

request.encoding = 'gbk'

html = request.content

print(html)

return html

def get_proxie(random_number):

with open('ip.txt', 'r') as file:

ip_list = json.load(file)

if random_number == -1:

random_number = random.randint(0, len(ip_list) - 1)

ip_info = ip_list[random_number]

ip_url_next = '://' + ip_info['address'] + ':' + ip_info['port']

proxies = {'http': 'http' + ip_url_next, 'https': 'https' + ip_url_next}

return random_number, proxies

# 程序主入口

if __name__ == '__main__':

"""只是爬取了書(shū)籍的第一頁(yè),按照評價(jià)排序"""

start_time = datetime.datetime.now()

url = 'https://book.douban.com/tag/?view=type&icn=index-sorttags-all'

base_url = 'https://book.douban.com/tag/'

html = get_html(url)

soup = BeautifulSoup(html, 'lxml')

article_tag_list = soup.find_all(class_='tag-content-wrapper')

tagCol_list = soup.find_all(class_='tagCol')

for table in tagCol_list:

""" 整理分析數據 """

sub_type_list = []

a = table.find_all('a')

for book_type in a:

sub_type_list.append(book_type.text)

article_type_list.append(sub_type_list)

for sub in article_type_list:

for sub1 in sub:

title = '==============' + sub1 + '=============='

print(title)

print(base_url + sub1 + '?start=0' + '&type=S')

with open('book.text', 'a', encoding='utf-8') as f:

f.write('\n' + title + '\n')

f.write(url + '\n')

for start in range(0, 2):

# (start * 20) 分頁(yè)是0 20 40 這樣的

# type=S是按評價(jià)排序

url = base_url + sub1 + '?start=%s' % (start * 20) + '&type=S'

html = get_html(url)

soup = BeautifulSoup(html, 'lxml')

li = soup.find_all(class_='subject-item')

for div in li:

info = div.find(class_='info').find('a')

img = div.find(class_='pic').find('img')

content = '書(shū)名:<%s>' % info['title'] + ' 書(shū)本圖片:' + img['src'] + '\n'

print(content)

with open('book.text', 'a', encoding='utf-8') as f:

f.write(content)

end_time = datetime.datetime.now()

print('耗時(shí): ', (end_time - start_time).seconds)

  為什么選擇國外高匿代理!

  

  總結

  使用這樣簡(jiǎn)單的代理IP,基本上就可以應付在爬爬爬著(zhù)被封IP的情況了.而且沒(méi)有使用自己的IP,間接的保護?!?!

  大家有其他的愈發(fā)快捷的方式,歡迎你們可以拿出來(lái)交流和討論爬蟲(chóng)代理,謝謝。

0 個(gè)評論

要回復文章請先登錄注冊


官方客服QQ群

微信人工客服

QQ人工客服


線(xiàn)

最近中文字幕2019高清,亚洲人成高清在线播放,男生淦哭男生图片动漫有字,国产亚洲精品九九久在线观看,无码av专区丝袜专区