前言

本文仅记录一次学习爬虫的实验过程
糗事百科是一个发布糗事笑话的网站,用户不用登录账号就可以访问。

1、分析糗事百科网站

1.1 观察

打开糗百首页 https://www.qiushibaike.com/, 可看到有“热门”、“24小时”、“热图”、“文字”、“穿越”、“糗图”、“新鲜”等几个分类,点开某个分类,只能显示13页的文章,而本次实验是要爬取尽可能多的文章,显然这样不符合本次需求。点开某一个笑话可看到网址变成类似于这样“https://www.qiushibaike.com/article/121175659”, 即糗事百科的文章是由“https://www.qiushibaike.com/article/” 和一串数字组成的,在这里我把这串数字称为文章id。点开首页最新的文章(2018年12月18日),显示的文章id为121356768,点穿越分类下的文章,会随机跳转到历史某一天的文章,例如2010年5月9日有个文章的id是‘268312’,说明糗事百科的文章id是按文章的发布时间从小到大排列的。

1.2 验证猜想

随便输入一个数字,比如123,即访问址 “https://www.qiushibaike.com/article/123”, 发现确实能跳转到某一篇文章,但是网址末尾的数字变了,说明123这个文章id不存在,当文章id不存在时,糗百会自动跳转到随机的一篇文章。

1.3 爬取思路

遍历从0到最新的文章id,即range(0,121359999)这个区间内的数字,比如想验证‘123456’这个文章id是否存在,只需要获取网址 https://www.qiushibaike.com/article/123456 的网页源代码

  • 如果有123456这个文章id,那么在网页源代码中会有一行href=\"//www.qiushibaike.com/article/123456\"
  • 如果不存在123456,那么对应的href=\"//www.qiushibaike.com/article/xxxx\"就会变成其他数字

此时只需要看123456xxxx是否相等就可判断出结果。

1.4 需要注意的问题

  • 需要用代理ip爬取,不然爬取次数过多,会让输入验证码
  • 开启多线程加快爬取速度

2、爬虫代码

分两个文件,一个是获取代理ip,另一个是多线程爬取文章id

获取代理ip的文件 dailitest.py内容如下:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import requests,threading,datetime
from bs4 import BeautifulSoup
import random

\"\"\"
1、抓取西刺代理网站的代理ip
2、并根据指定的目标url,对抓取到ip的有效性进行验证
3、最后存到指定的path
\"\"\"

# ------------------------------------------------------文档处理--------------------------------------------------------
# 写入文档
def write(path,text):
    with open(path,\'a\', encoding=\'utf-8\') as f:
        #writelines可以把列表内容逐个写到文本文件中,此处换成write也可以
        f.writelines(text)
        f.write(\'\\n\')
# 清空文档
def truncatefile(path):
    with open(path, \'w\', encoding=\'utf-8\') as f:
        #f.truncate(5)会截取从文件开头到5字节大小的长度,为空或0size表示清空文件
        f.truncate()
# 读取文档,此处读取文档主要是为了统计有效ip的个数
def read(path):
    with open(path, \'r\', encoding=\'utf-8\') as f:
        txt = []
        for s in f.readlines():
            txt.append(s.strip())
    return txt
# ----------------------------------------------------------------------------------------------------------------------
# 计算时间差,格式: 时分秒
def gettimediff(start,end):
    #.seconds获取时间差,最大值小于86400s(一天的秒数),而.total_seconds是所有时间差
    seconds = (end - start).total_seconds()
    #divmod(7,2)会返回(3,1),即7除以2,商是3,余数是1
    m, s = divmod(seconds, 60)
    h, m = divmod(m, 60)
    d, h = divmod(h,24)
    diff = (\"%02d天%02d:%02d:%02d\" % (d,h, m, s))
    return diff
# ----------------------------------------------------------------------------------------------------------------------
# 返回一个随机的请求头 headers
def getheaders():
    user_agent_list = [
        \"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/22.0.1207.1 Safari/537.1\",
        \"Mozilla/5.0 (X11; CrOS i686 2268.111.0) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.57 Safari/536.11\",
        \"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.6 (KHTML, like Gecko) Chrome/20.0.1092.0 Safari/536.6\",
        \"Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.6 (KHTML, like Gecko) Chrome/20.0.1090.0 Safari/536.6\",
        \"Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/19.77.34.5 Safari/537.1\",
        \"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.9 Safari/536.5\",
        \"Mozilla/5.0 (Windows NT 6.0) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.36 Safari/536.5\",
        \"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1063.0 Safari/536.3\",
        \"Mozilla/5.0 (Windows NT 5.1) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1063.0 Safari/536.3\",
        \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_0) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1063.0 Safari/536.3\",
        \"Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1062.0 Safari/536.3\",
        \"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1062.0 Safari/536.3\",
        \"Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1061.1 Safari/536.3\",
        \"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1061.1 Safari/536.3\",
        \"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1061.1 Safari/536.3\",
        \"Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1061.0 Safari/536.3\",
        \"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.24 (KHTML, like Gecko) Chrome/19.0.1055.1 Safari/535.24\",
        \"Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/535.24 (KHTML, like Gecko) Chrome/19.0.1055.1 Safari/535.24\"
    ]
    UserAgent=random.choice(user_agent_list)
    headers = {\'User-Agent\': UserAgent}
    return headers
# -----------------------------------------------------检查ip是否可用----------------------------------------------------
def checkip(targeturl,ip):
    headers =getheaders()  # 定制请求头
    proxies = {\"http\": \"http://\"+ip, \"https\": \"http://\"+ip}  # 代理ip
    try:
        response=requests.get(url=targeturl,proxies=proxies,headers=headers,timeout=5).status_code
        if response == 200 :
            return True
        else:
            return False
    except:
        return False

#-------------------------------------------------------获取代理方法----------------------------------------------------
# 免费代理 XiciDaili
def findip(type,pagenum,targeturl,path): # ip类型,页码,目标url,存放ip的路径
    list={\'1\': \'http://www.xicidaili.com/nt/\', # xicidaili国内普通代理
          \'2\': \'http://www.xicidaili.com/nn/\', # xicidaili国内高匿代理
          \'3\': \'http://www.xicidaili.com/wn/\', # xicidaili国内https代理
          \'4\': \'http://www.xicidaili.com/wt/\'} # xicidaili国外http代理
    url=list[str(type)]+str(pagenum) # 配置url
    headers = getheaders() # 定制请求头
    html=requests.get(url=url,headers=headers,timeout = 5).text
    soup=BeautifulSoup(html,\'l \')
    all=soup.find_all(\'tr\',class_=\'odd\')
    for i in all:
        t=i.find_all(\'td\')
        ip=t[1].text+\':\'+t[2].text
        is_avail = checkip(targeturl,ip)
        if is_avail == True:
            write(path=path,text=ip)
            print(ip)

#-----------------------------------------------------多线程抓取ip入口---------------------------------------------------
def getip(targeturl,path):
     truncatefile(path) # 爬取前清空文档
     start = datetime.datetime.now() # 开始时间
     threads=[]
     for type in range(4):   # 四种类型ip,每种类型取前三页,共12条线程
         for pagenum in range(3):
             t=threading.Thread(target=findip,args=(type+1,pagenum+1,targeturl,path))
             threads.append(t)
     print(\'开始爬取代理ip\')
     for s in threads: # 开启多线程爬取
         s.start()
     for e in threads: # 等待所有线程结束
         e.join()
     print(\'爬取完成\')
     end = datetime.datetime.now() # 结束时间
     diff = gettimediff(start, end)  # 计算耗时
     ips = read(path)  # 读取爬到的ip数量
     print(\'一共爬取代理ip: %s 个,共耗时: %s \\n\' % (len(ips), diff))

#-------------------------------------------------------启动-----------------------------------------------------------
# if __name__ == \'__main__\':
def start_ip():
    path = \'ip.txt\' # 存放爬取ip的文档path
    #targeturl = \'http://www.cnblogs.com/TurboWay/\' # 验证ip有效性的指定url
    targeturl = \'https://www.qiushibaike.com/\'
    getip(targeturl,path)

多线程爬取文章id qsbk_id.py内容如下:

# _*_ coding:utf-8 _*_
import requests
import re
import time
import random
import dailitest
import threading
import datetime

#获取可用ips[]列表
def get_ips():
    dailitest.start_ip()
    ips = []
    filename = \'ip.txt\'
    with open(filename, \'r\') as f_open:
        for line in f_open.readlines():
            ips.append(line.strip())
    return ips

#将可用article_num写入文件
def yanzheng_ip(url,headers,proxies,article_id):
    request = requests.get(url=url, headers=headers, proxies=proxies, timeout=5)
    response = request.text
    pattern = r\'href=\"//www.qiushibaike.com/article/(.*?)\"\'
    num_list = re.findall(pattern, response)
    if len(num_list) > 0:
        num = num_list[0]
        if str(article_id) == num:
            print(\'已找到一个\')
            filename = \'qsbk_id.txt\'
            with open(filename, \'a\', encoding=\'utf-8\') as f_open:
                f_open.write(\'\\n\' + num)
        else:
            print(article_id)
    else:
        print(article_id)
    return

#收集因代理ip失效导致跳过的article_num
def tiaoguo_num(fail_num):
    filename = \'fail_article_num.txt\'
    with open(filename,\'a\',encoding=\'utf-8\') as f_open:
        f_open.writelines(fail_num)
        f_open.write(\'\\n\')

def single_thread(ips,article_id):
    ip = random.choice(ips)
    proxies = {\"http\": \"http://\" + ip, \"https\": \"http://\" + ip}
    url = \'https://www.qiushibaike.com/article/\' + str(article_id)
    try:
        yanzheng_ip(url,headers,proxies,article_id)

    except:
        print(\'代理ip失效:%s,还剩%d个代理ip\' % (ip,len(ips)))
        print(article_id)
        fail_num = str(article_id)
        tiaoguo_num(fail_num)
        ips.remove(ip)

#每次10个线程爬取,从30000000开始
def many_threads(ips):
    threads = []
    y1 = 1
    max = 121400000
    for x9 in range(2):
        if y1 > max:
            break
        y9 = 100000000 * x9
        for x8 in range(3, 10):
            if y1 > max:
                break
            y8 = 10000000 * x8
            for x7 in range(10):
                if y1 > max:
                    break
                y7 = 1000000 * x7
                for x6 in range(10):
                    if y1 > max:
                        break
                    y6 = 100000 * x6
                    for x5 in range(10):
                        if y1 > max:
                            break
                        y5 = 10000 * x5
                        for x4 in range(10):
                            if y1 > max:
                                break
                            y4 = 1000 * x4
                            for x3 in range(10):
                                if y1 > max:
                                    break
                                y3 = 100 * x3
                                for x2 in range(10):
                                    if y1 > max:
                                        break
                                    y2 = 10 * x2
                                    for x1 in range(10):
                                        if y1 > max:
                                            break
                                        y1 = y9 + y8 + y7 + y6 + y5 + y4 + y3 + y2 + x1
                                        if y1 % 2000 == 0:
                                            time.sleep(600)
                                        if len(ips) < 10:
                                            ips = get_ips()
                                        t = threading.Thread(target=single_thread, args=(ips,y1))
                                        threads.append(t)
                                    for s in threads:  # 开启多线程爬取
                                        if not t.is_alive():
                                            s.start()
                                    for e in threads:  # 等待所有线程结束
                                        e.join()
                                    threads = []

headers = dailitest.getheaders()
# ips = []

#for article_id  in range(36885710,121344691):


ips = []
start = datetime.datetime.now()
many_threads(ips)
end = datetime.datetime.now()
diff = dailitest.gettimediff(start,end)
print(\'耗时\' + diff)

3、爬取结果截图如下:

回头再补

收藏 打印