Python学习三: 爬虫高级技巧 与 模拟实战练习

三大爬虫技巧

许多网站针对爬虫的访问都设置了一定的障碍,通过这三步技巧,轻松绕过部分的反爬虫限制。

(1)设置程序休止时间

import time
import random

# 休止睡眠 1 秒 这里秒可自定义
time.sleep(1);
# 随机休眠0或者1秒
random.random();
# 随机休眠1或者5秒
time_interval = random .uniform(1,5) 
time.sleep(time_interval)

(2)设置代理

设置代理,代理IP又分三种代理ID:

  1. 低级别(Transparent Proxy) :服务器知道你在使用代理,且知道你的真实IP
  2. 中级别(AnonyMous Proxy) :服务器知道你在使用代理,但不知道你的真实IP
  3. 高级别(Elite Proxy / Highly AnonyMous Proxy):服务器不知道你在使用代理

代理服务器的存在,可以应对网站禁止某个IP访问的反爬虫措施,代理服务器有着不同的匿名类型,通常我们会挑选中、高级别的代理服务器来访问网页。

#使用urllib.request的两个方法进行代理的设置
proxy = urlrequest.ProxyHandler({'https':'24.245.100.212:48678'});
opener = urlrequest.build_opener(proxy);

这里我常用的是 小幻HTTP代理

因为是免费IP,如果不使用请不要长时间占用。

(3)伪装浏览器访问

我们使用Python编码进行数据爬取时,网站是可以识别你是否在使用Python进行爬取,需要你在发送网络请求时,把header部分通过Pyton伪装成浏览器的 User-Agent 的信息。

# 伪装浏览器访问
opener.addheaders = [('User-Agent','Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_4) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/10.1 Safari/603.1.30')]
urlrequest.install_opener(opener)

至于 User-Agent 的信息请自行百度。

练习一:Place Pulse Google街景图爬取

首先,我使用的是外网的一个统计页面,统计出的数据集,这个页面会从谷歌地图中抓取两个街景,并进行对比提问,比如这两张图片中你认为那个更富有.....之类的提问。(PLACE PULSE

这里如果打不开这个网站,我把数据集上传到CSDN:https://download.csdn.net/download/qq_33081367/10595924

import urllib.request as urlrequest
import time
import random

# 载入包,定义存储目录,连接API
IMG_PATH = "./img/{}.jpg";
# 数据集
DATA_FILE = "./data/votes.csv";
# 下载过图片ID文档
STORED_IMG_ID_FILE = './data/cached_img.txt';
STORED_IMG_IDS = set();
# 这里是Google 下载图片的 url
IMG_URL = 'https://maps.googleapis.com/maps/api/streetview?size=400x300&location={},{}';

# 使用代理服务器、User-Agent
proxy = urlrequest.ProxyHandler({'https':'24.245.100.212:48678'});
opener = urlrequest.build_opener(proxy);
opener.addheaders = [('User-Agent','Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_4) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/10.1 Safari/603.1.30')]
urlrequest.install_opener(opener)

# 读取图片的id (我这里把下载过的图片ID存储起来,在抓取图片时进行对比防止重复抓取)
with open(STORED_IMG_ID_FILE) as input_file :
    for line in input_file :
        STORED_IMG_IDS.add(line.strip())

# 根据提供的图片id文档,进行google街景图片的爬取
with open(DATA_FILE) as input_file :
    # 因为文档第一行是存储的字段 所以第一行直接跳过
    skip_first_line = True ;
    for line in input_file :
        if skip_first_line :
            skip_first_line = False;
            continue;
        # 这里把文档中的值赋值字段中进行操作
        left_id, right_id, winner, left_lat, left_long, right_lat, right_long, category = line.split(",");
        # 判断图片ID 是否下载过
        if left_id not in STORED_IMG_IDS :
            print('saving img {}...'.format(left_id))
            # urlretrieve 可以直接下载图片内容
            urlrequest.urlretrieve(IMG_URL.format(left_lat,left_long),IMG_PATH.format(left_id));
            STORED_IMG_IDS.add(left_id);
            with open(STORED_IMG_ID_FILE,"a") as output_file :
                output_file.write("{}\n".format(left_id))
            time.sleep(1);

        if right_id not in STORED_IMG_IDS :
            print('saving img {}...'.format(right_id))
            # urlretrieve 可以直接下载图片内容
            urlrequest.urlretrieve(IMG_URL.format(right_lat,right_long),IMG_PATH.format(right_id))
            STORED_IMG_IDS.add(right_id)
            with open(STORED_IMG_ID_FILE,'a') as output_file :
                output_file.write("{}\n".format(right_id))
            random.random();

这里我使用的 PyChram 编写的,运行结果如下:

练习二:豆瓣电影Top250

这里做一个练习,通过之前所学把豆瓣电影的 TOP250 爬取下来。

这里我还是推荐大家使用Jupyter进行编写,锻炼自己的编写能力,下面是我自己写的Python代码与运行结果:

import urllib.request as urlrequest
from bs4 import BeautifulSoup

http_url = 'https://movie.douban.com/top250?start={}&filter='

for i in range(10):
    i = i * 25
    url = http_url.format(i)
    url_content = urlrequest.urlopen(url).read().decode('utf8')
    soup = BeautifulSoup(url_content,'html.parser')
    item_div = soup.find_all(class_='item')
    for item in item_div :
        alt_name = item.find(class_='pic').find('img')['alt']
        href_url = item.find('a')['href']
        print('{} {} \n'.format(alt_name,href_url))

练习三:腾讯游戏今日新闻

网址:http://games.qq.com/

爬取要求:包含每个新闻的标题、链接、文字内容

import urllib.request as urlrequest
from bs4 import BeautifulSoup

http_url = 'http://games.qq.com/'
opener = urlrequest.build_opener()
opener.addheaders= [('User-Agent','Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_4) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/10.1 Safari/603.1.30')]
urlrequest.install_opener(opener)
url_content = urlrequest.urlopen(http_url).read().decode('gbk')
soup = BeautifulSoup(url_content,'html.parser')
all_top_news = soup.find(class_='section section0')
top_news_h3 = all_top_news.find_all('h3')
for item in top_news_h3 : 
    item_href = item.find('a')['href']
    item_name = item.find('a').get_text()
    item_content = []
    #获取正文
    try :#由于新闻的正文可能只有图片没有文字,所以这里增加了一个异常处理的方式try/except
        url = urlrequest.urlopen(item_href).read().decode('gbk')
        content_soup = BeautifulSoup(url,'html.parser')
        content = content_soup.find(class_='content clearfix')
        alltext = content.find_all('p')
        for i in alltext:
            item_content.append(i.get_text())
    except :#意思就是,如果出现错误,直接跳过
        pass

    print(' {} {} {} \n'.format(item_name,item_href,item_content))

运行结果如下:

练习四:爬取小猪短租的页面信息(以成都为例)

需爬取的信息如下:(标题、链接、位置、评分) 
地址如下 http://cd.xiaozhu.com/ 

import urllib.request as urlrequest
from bs4 import BeautifulSoup

origin_url ="http://cd.xiaozhu.com/search-duanzufang-p{}-0/"
with open('xiaozhu.txt','w') as outputfile:
    #翻页
    for i in range(1,6):#括号里表示页数,获取1-5页的所有房源信息
        url=origin_url.format(i)        
        content=urlrequest.urlopen(url).read().decode('utf8')
        soup=BeautifulSoup(content,'html.parser')
        allurls=soup.find_all(class_='resule_img_a')
        #获取详细信息网址
        for j in allurls:
            list1=[]
            list1.append(j.get('href'))
            #解析详细信息网址
            for href in list1:
                content2=urlrequest.urlopen(href).read().decode('utf8')
                soup2=BeautifulSoup(content2,'html.parser')
                title=soup2.find('title').get_text()#标题
                location=soup2.find(class_='pr5').get_text()#地址
                score=soup2.find(class_='top_bar_w2 border_right_none').get_text()#评分
                #写入文件
                outputfile.write('\n{}\n{}\n{}\n{}\n'.format(title,href,location,score))

爬虫补充技巧 

1.动态设置user agent部分

阅读Python爬虫基础 | 爬虫反ban的技巧中动态设置header的部分

2.验证码识别

不少网站使用验证码来拦截爬虫,怎么来越过这些验证码的障碍是你需要学习的。

3.Selenium

Selenium就是一个真实的浏览器,是在网站的拦截范围之外的。

4.相关爬虫技巧的总结:

5.有意思的爬虫应用

本次课程主要以豆瓣视频、气象网站信息为例,除此之外,爬虫还可以实现更多更有意思的事情。阅读以下链接的内容,扩展你关于爬虫实现功能的认知。

6.推荐给你继续爬虫任务的网站

7.阅读材料

对于学有余力的你,推荐以下三本书籍进行阅读。

猜你喜欢

转载自blog.csdn.net/qq_33081367/article/details/81564373