请选择 进入手机版 | 继续访问电脑版

VRPIP 虚拟化平台

 找回密码
 注册VRPIP
搜索
热搜: 活动 交友 discuz
查看: 18105|回复: 1

小白 学pyton 爬虫六

[复制链接]

8

主题

11

帖子

55

积分

注册会员

Rank: 2

积分
55
发表于 2020-10-5 22:35:39 | 显示全部楼层 |阅读模式
本帖最后由 Tinken 于 2020-10-7 01:29 编辑

实战:爬当当网图书(http://www.dangdang.com/)废话少说,经过分析,当当网图书的url均为:http://product.dangdang.com/xxxxxx.html
xxxxxx:为一串数字,可能是当当网自己的图书编号吧,这个就帮忙大忙了,弄起来就方便了

一、随便找一本书的地址,对html进行分析,拿到自己想要的数据内容
二、将拿到的数据内容写入Excel
三、做一个循环,从http://product.dangdang.com/1.html开始,出错就跳过,没出错就继续拿
四、用到刚写的ip代理池,一定不能用自己ip干这事
五、考虑到数据量太大,我们还得做一个记录,分批爬

开干:
  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-

  3. # @ClassName test7
  4. # @Description TODO 爬当当网全部图书数据
  5. # @Author lanlo
  6. # @Date 2020-10-05 22:36
  7. # @Version 1.0

  8. import requests
  9. from bs4 import BeautifulSoup
  10. import redis
  11. # Excel操作库
  12. import xlwings as xw
  13. # 系统时间库
  14. import time
  15. import proxy_pool
  16. import re


  17. # 本地redis连接
  18. pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
  19. # 存储爬取的代理ip
  20. redis_conn = redis.Redis(connection_pool=pool, max_connections=10, db=0)




  21. # xlwings 写入Excel => books.xlsx
  22. def writeExcel(list):
  23.     # 这将创建一个新的工作簿
  24.     wb = xw.Book('books.xlsx')
  25.     # 实例化工作表对象
  26.     sht = wb.sheets['Sheet1']
  27.     sht.api.Rows(1).Insert()
  28.     sht.range('A1').value = list
  29.     # 保存
  30.     wb.save()

  31. def get_book():
  32.     # 模拟浏览器的请求头
  33.     headers = {
  34.         'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36 Edg/ 5.0.564.68'
  35.     }
  36.     proxy = proxy_pool.get_proxy_ip()

  37.     # proxy = {
  38.     #     'http': '218.7.171.91:3128'
  39.     # }

  40.     if len(proxy) != 0:
  41.         # 拼接url
  42.         for i in range(27866721, 27866722):
  43.             url = "http://product.dangdang.com/{}.html".format(str(i))
  44.             try:
  45.                 # 发起http请求,获取页面
  46.                 print("请求页面:{}".format(url))
  47.                 res = requests.get(url,
  48.                                    headers=headers,
  49.                                    proxies=proxy,
  50.                                    timeout=5)
  51.             except Exception:
  52.                 print("请求失败:{}".format(url))
  53.                 print("代理ip:{}".format(proxy))
  54.                 return ""


  55.             print("请求结果:{}".format(res.status_code))
  56.             # 设置解析器
  57.             soup = BeautifulSoup(res.text, "html.parser")
  58.             # 获得数据内容
  59.             print(soup)
  60.             # 书名
  61.             title = soup.find_all('h1')[0].text.replace("\n", '').replace("\t", "").replace(" ", "")
  62.             print("书名:{}".format(title))
  63.             # 作者
  64.             print("作者:{}".format(soup.find_all("a", dd_name='作者')[0].string))

  65.             # 出版社
  66.             print("出版社:{}".format(soup.find_all("a", dd_name='出版社')[0].string))

  67.             # 出版时间
  68.             print("出版时间:{}".format(soup.find_all("span", string=re.compile("出版时间"))[0].string.split(":")[1]))

  69.             list_book = []
  70.             for child in soup.find_all("ul", class_='key clearfix')[0]:
  71.                 book_info = str(child.string).replace("\n", '').replace("\t", "").replace(" ", "")
  72.                 if book_info != "" and book_info != None:
  73.                     print(book_info)
  74.                     list_book.append(book_info)
  75.             print(list_book)

  76.             # 分类
  77.             print("分类:{}".format(soup.find_all("li", class_="clearfix fenlei")[0].text))


  78.             # 延时3秒
  79.             time.sleep(3)
  80.     print("get_book 结束")



  81. # python程序入口函数
  82. if __name__ == '__main__':
  83.     # 星期 月 日 时:分:秒 年(Mon Oct  5 23:10:13 2020)
  84.     print("程序开始时间:{}".format(time.ctime()))
  85.     get_book()
复制代码

暂时先这样吧,页面分析做出来了,明天添加写入Excel功能就可以完工了
不过还有几个遗留问题待处理:
代理ip如何自动切换
如何保存已爬取的记录,当当网应该有几千万或者上亿条数据吧
是否需要二次或者多次爬取,做重复验证

声明:本文仅学习使用,如有侵权或者因个人行为造成不良影响,请通知我删除。谢谢!


回复

使用道具 举报

8

主题

11

帖子

55

积分

注册会员

Rank: 2

积分
55
 楼主| 发表于 2020-10-8 00:58:57 | 显示全部楼层
本帖最后由 Tinken 于 2020-10-8 01:06 编辑

今天没有太多时间,晚上花了点时间调整Excel写入,现在基本搞定剩余就是ip切换和异常处理,然后后面需要使用while死循环,避免因为异常而中断


代码:
  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-

  3. # @ClassName test7
  4. # @Description TODO 爬当当网全部图书数据
  5. # @Author lanlo
  6. # @Date 2020-10-05 22:36
  7. # @Version 1.0

  8. import requests
  9. from bs4 import BeautifulSoup
  10. import redis
  11. # Excel操作库
  12. import xlwings as xw
  13. # 系统时间库
  14. import time
  15. import proxy_pool
  16. import re

  17. # 本地redis连接
  18. pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
  19. # 存储爬取的代理ip
  20. redis_conn = redis.Redis(connection_pool=pool, max_connections=10, db=0)

  21. # xlwings 写入Excel => books.xlsx
  22. def writeExcel(list):
  23.     # 这将创建一个新的工作簿
  24.     wb = xw.Book('books.xlsx')
  25.     # 实例化工作表对象
  26.     sht = wb.sheets['Sheet1']
  27.     sht.api.Rows(1).Insert()
  28.     sht.range('A1').value = list
  29.     # 保存
  30.     wb.save()

  31. def get_book():
  32.     # 模拟浏览器的请求头
  33.     headers = {
  34.         'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36 Edg/ 5.0.564.68'
  35.     }
  36.     proxy = proxy_pool.get_proxy_ip()

  37.     if len(proxy) != 0:
  38.         # 拼接url
  39.         for i in range(27866721, 27866800):
  40.             list_book = []
  41.             url = "http://product.dangdang.com/{}.html".format(str(i))
  42.             try:
  43.                 # 发起http请求,获取页面
  44.                 print("请求页面:{}".format(url))
  45.                 res = requests.get(url,
  46.                                    headers=headers,
  47.                                    proxies=proxy,
  48.                                    timeout=5)
  49.             except Exception:
  50.                 print("请求失败:{}".format(url))
  51.                 print("代理ip:{}".format(proxy))
  52.                 list_book.append("请求失败")
  53.                 pass

  54.             res_code = res.status_code
  55.             list_book.append(url)
  56.             print("请求结果:{}".format(res_code))
  57.             if res_code == 200:
  58.                 # 设置解析器
  59.                 soup = BeautifulSoup(res.text, "html.parser")
  60.                 # 获得数据内容
  61.                 print(soup.prettify())

  62.                 # 书名
  63.                 title = soup.find_all('h1')[0].text.replace("\n", '').replace("\t", "").replace(" ", "")
  64.                 list_book.append(title)
  65.                 print("书名:{}".format(title))

  66.                 # 作者
  67.                 author = soup.find_all("a", dd_name='作者')[0].string
  68.                 list_book.append(author)
  69.                 print("作者:{}".format(author))

  70.                 # 出版社
  71.                 press = soup.find_all("a", dd_name='出版社')[0].string
  72.                 list_book.append(press)
  73.                 print("出版社:{}".format(press))

  74.                 # 出版时间
  75.                 publication_time = soup.find_all("span", string=re.compile("出版时间"))[0].string.split(":")[1].replace("\n", '').replace("\t", "").replace(" ", "")
  76.                 list_book.append(publication_time)
  77.                 print("出版时间:{}".format(publication_time))

  78.                 for child in soup.find_all("ul", class_='key clearfix')[0]:
  79.                     book_info = str(child.string).replace("\n", '').replace("\t", "").replace(" ", "").replace("None", "")
  80.                     if book_info != "":
  81.                         print(book_info.split(":")[1])
  82.                         list_book.append(book_info.split(":")[1])

  83.                 # 分类
  84.                 book_class = soup.find_all("li", class_="clearfix fenlei")[0].text.split(":")[1]
  85.                 list_book.append(book_class)
  86.                 print("分类:{}".format(book_class))

  87.                 print(list_book)


  88.             else:
  89.                 list_book.append("请求失败")

  90.             # 写入Excel
  91.             writeExcel(list_book)

  92.             # 延时3秒
  93.             time.sleep(3)
  94.     print("get_book 结束")



  95. # python程序入口函数
  96. if __name__ == '__main__':
  97.     # 星期 月 日 时:分:秒 年(Mon Oct  5 23:10:13 2020)
  98.     print("程序开始时间:{}".format(time.ctime()))
  99.     get_book()
复制代码
最后稍微处理一下,添加表头:



本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有帐号?注册VRPIP

x
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册VRPIP

本版积分规则

快速回复 返回顶部 返回列表