目录
前言
爬虫概述
爬虫实现
1. 获取代理IP
2. 爬取数据
3. 多线程爬取
总结
随着互联网和智能设备的普及,数据量逐年增长,数据分析和挖掘成为了热门领域,其中大数据分析技术和爬虫技术是重要的手段之一。本文主要介绍如何使用Python编写爬虫程序,通过代理IP,爬取数据进行分析。
爬虫是指一种自动化获取并处理各种互联网信息的程序。爬虫程序可以根据特定的规则和算法,自动化地从互联网上抓取信息,支持对抓取到的信息进行自动化处理、筛选和分析等操作。
与普通的网页浏览器不同,爬虫可以批量自动获取特定网站的信息,且可以通过一定的方式绕开网站的禁止爬虫机制,支持对网站进行长期大量抓取。
我们以爬取[豆瓣电影TOP250](https://movie.douban.com/top250)为例进行介绍。我们使用Python语言和requests、BeautifulSoup4等第三方库进行编写。
在爬取数据的过程中,我们需要使用多个代理IP来绕过网站的限制。我们可以通过以下代码获取免费代理IP:
import requests
from bs4 import BeautifulSoup
def get_proxies():
url = 'https://www.zdaye.com/'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}
r = requests.get(url, headers=headers)
soup = BeautifulSoup(r.text, 'html.parser')
trs = soup.find_all('tr')
ips = []
for tr in trs[1:]:
tds = tr.find_all('td')
ip = tds[1].text + ':' + tds[2].text
ips.append(ip)
return ips
该函数通过访问站大爷代理IP(https://www.zdaye.com/)获取代理IP,返回一个代理IP列表。
为了防止被网站识别出爬虫的行为并限制我们的访问,我们需要设置一些请求头和代理IP。我们可以通过以下代码实现:
import requests
from bs4 import BeautifulSoup
import random
import time
headers_list = [{'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'},
{'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36'},
{'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36'},
{'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.83 Safari/537.36'},
{'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 Edge/16.16299'},
{'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; Trident/7.0; AS; rv:11.0) like Gecko'},
{'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36 Edge/16.16299'},
{'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:54.0) Gecko/20100101 Firefox/54.0'},
{'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; Trident/7.0; AS; rv:11.0) like Gecko'},]
def get_movie_info(url, proxies):
headers = random.choice(headers_list)
proxy = random.choice(proxies)
proxies = {'http': 'http://' + proxy, 'https': 'https://' + proxy}
try:
r = requests.get(url, headers=headers, proxies=proxies, timeout=10)
if r.status_code == 200:
soup = BeautifulSoup(r.text, 'html.parser')
title = soup.find('div', class_='title_wrapper').h1.text.strip()
rating = soup.find('span', itemprop='ratingValue').text
director = soup.find('h4', text='Director:').next_sibling.text.strip()
actors = [a.text.strip() for a in soup.find_all('span', itemprop='name')]
genre = [a.text.strip() for a in soup.find_all('span', itemprop='genre')]
country = soup.find('h4', text='Country:').next_sibling.text.strip()
language = soup.find('h4', text='Language:').next_sibling.text.strip()
release_date = soup.find('h4', text='Release Date:').next_sibling.text.strip()
return {'title': title, 'rating': rating, 'director': director, 'actors': actors, 'genre': genre, 'country': country, 'language': language, 'release_date': release_date}
else:
print('Request Failed ' + url)
return None
except:
print('Request Failed ' + url)
return None
该函数通过随机选择请求头和代理IP,获取特定电影的相关信息,并返回一个字典。
当我们需要爬取大量数据时,单线程爬取速度较慢,效率不高。我们可以使用多线程技术提高爬取效率。下面是一个实现多线程爬取的函数:
import threading
from queue import Queue
class CrawlerThread(threading.Thread):
def __init__(self, crawler, url_queue, proxies):
threading.Thread.__init__(self)
self.crawler = crawler
self.url_queue = url_queue
self.proxies = proxies
def run(self):
while True:
url = self.url_queue.get()
if url is None:
break
movie_info = self.crawler(url, self.proxies)
if movie_info is not None:
print(movie_info)
self.url_queue.task_done()
def crawler_worker(crawler, url_queue, proxies):
for i in range(5):
CrawlerThread(crawler, url_queue, proxies).start()
url_queue.join()
for i in range(5):
url_queue.put(None)
def crawl_movies(crawler, urls, proxies):
url_queue = Queue()
for url in urls:
url_queue.put(url)
crawler_worker(crawler, url_queue, proxies)
该函数通过启动多个线程,实现多个爬虫同时爬取数据。我们可以通过以下代码调用该函数:
proxies = get_proxies()
urls = ['https://movie.douban.com/top250?start={}&filter='.format(i * 25) for i in range(10)]
crawl_movies(get_movie_info, urls, proxies)
本文主要介绍了如何利用Python编写爬虫程序,通过代理IP,爬取数据进行分析。爬虫程序是一种重要的数据采集工具,具有高效、灵活、自动化等优点。在实际应用