Day-9 python

一、昨日作业

  1 '''
  2 主页:
  3     图标地址、
  4     https://www.wandoujia.com/category/6001
  5 
  6 
  7 
  8     32
  9 '''
 10 
 11 import requests
 12 from bs4 import BeautifulSoup
 13 from pymongo import MongoClient
 14 
 15 # 连接MongoDB客户端
 16 client = MongoClient('localhost', 27017)
 17 # 创建或选择wangdoujia库,index集合
 18 index_col = client['wangdoujia']['index']
 19 # 创建或选择wangdoujia库,detail集合
 20 detail_col = client['wangdoujia']['detail']
 21 
 22 # 1、发送请求
 23 def get_page(url):
 24     response = requests.get(url)
 25     return response
 26 
 27 # 2、开始解析
 28 # 解析详情页
 29 def parse_detail(text):
 30 
 31     soup = BeautifulSoup(text, 'lxml')
 32     # print(soup)
 33 
 34     try:
 35         name = soup.find(name="span", attrs={"class": "title"}).text
 36     except Exception:
 37         name = None
 38 
 39 
 40 
 41     try:
 42         love = soup.find(name='span', attrs={"class": "love"}).text
 43     except Exception:
 44         love = None
 45 
 46 
 47 
 48     try:
 49         commit_num = soup.find(name='a', attrs={"class": "comment-open"}).text
 50     except Exception:
 51         commit_num = None
 52 
 53 
 54     try:
 55         commit_content = soup.find(name='div', attrs={"class": "con"}).text
 56     except Exception:
 57         commit_content = None
 58 
 59 
 60     try:
 61         download_url = soup.find(name='a', attrs={"class": "normal-dl-btn"}).attrs['href']
 62     except Exception:
 63         # 若有异常,设置为None
 64         download_url = None
 65 
 66 
 67     if name and love and commit_num and commit_content and download_url:
 68         detail_data = {
 69             'name': name,
 70             'love': love,
 71             'commit_num': commit_num,
 72             'download_url':download_url
 73         }
 74 
 75     if not love:
 76         detail_data = {
 77             'name': name,
 78             'love': '没有点赞',
 79             'commit_num': commit_num,
 80             'download_url': download_url
 81         }
 82     if not download_url:
 83         detail_data = {
 84             'name': name,
 85             'love': love,
 86             'commit_num': commit_num,
 87             'download_url':'没有安装包'
 88         }
 89 
 90 
 91     detail_col.insert(detail_data)
 92     print(f'{name}app数据插入成功!')
 93 
 94 # 解析主页
 95 def parse_index(data):
 96     soup = BeautifulSoup(data, 'lxml')
 97 
 98     # 获取所有app的li标签
 99     app_list = soup.find_all(name='li', attrs={"class": "card"})
100     for app in app_list:
101         # print('*' * 1000)
102         # print(app)
103         # 图标地址
104         # 获第一个img标签中的data-origina属性
105         img = app.find(name='img').attrs['data-original']
106         # print(img)
107 
108         # 下载次数
109         # 获取class为install-count的span标签中的文本
110         down_num = app.find(name='span',attrs={"class": "install-count"}).text
111         # print(down_num)
112 
113         # 大小
114         # 根据文本正则获取到文本中包含 数字 + MB (d+代表数字)的span标签中的文本
115         import re
116         size = soup.find(name='span', text=re.compile("d+MB")).text
117         # print(size)
118 
119         # 详情页地址
120         # 获取class为detail-check-btn的a标签中的href属性
121         detail_url = app.find(name='a').attrs['href']
122         # print(detail_url)
123 
124         # 拼接数据
125         index_data = {
126             'img':img,
127             'down_num':down_num,
128             'size': size,
129             'detail_url': detail_url
130         }
131 
132         index_col.insert(index_data)
133         print(f'主页数据插入成功')
134 
135         # 3、往app详情页发送请求
136         response = get_page(detail_url)
137         # print(response.text)
138         # print('tank')
139 
140         # 4、解析详情页
141         parse_detail(response.text)
142 
143 
144 def main():
145     for line in range(1,33):
146         url = f'https://www.wandoujia.com/wdjweb/api/category/more?catId=6001&subCatId=0&page={line}&ctoken=ql8VkarJqaE7VAYNAEe2JueZ'
147 
148         # 1、往app接口发送前请求
149         response = get_page(url)
150         # print(response.text)
151         print('*' * 1000)
152         # 反序列化为字典
153         data = response.json()
154         # 获取接口中app标签数据
155         app_li = data['data']['content']
156         # print(app_li)
157         # 2、解析app标签数据
158         parse_index(app_li)
159 
160         # 执行完所有函数关闭mongoDB客户端
161         client.close()
162 
163 
164 if __name__ == '__main__':
165     main()
今日内容:
0、MongoDB可视化工具

1、Scrapy爬虫框架

2、微信机器人

'''
Components:

1、引擎(EGINE)
引擎负责控制系统所有组件之间的数据流,并在某些动作发生时触发事件。有关详细信息,请参见上面的数据流部分。

2、调度器(SCHEDULER)
用来接受引擎发过来的请求, 压入队列中, 并在引擎再次请求的时候返回. 可以想像成一个URL的优先级队列, 由它来决定下一个要抓取的网址是什么, 同时去除重复的网址

3、下载器(DOWLOADER)
用于下载网页内容, 并将网页内容返回给EGINE,下载器是建立在twisted这个高效的异步模型上的

4、爬虫(SPIDERS)
SPIDERS是开发人员自定义的类,用来解析responses,并且提取items,或者发送新的请求

5、项目管道(ITEM PIPLINES)
在items被提取后负责处理它们,主要包括清理、验证、持久化(比如存到数据库)等操作
下载器中间件(Downloader Middlewares)位于Scrapy引擎和下载器之间,主要用来处理从EGINE传到DOWLOADER的请求request,已经从DOWNLOADER传到EGINE的响应response,
你可用该中间件做以下几件事:
  (1) process a request just before it is sent to the Downloader (i.e. right before Scrapy sends the request to the website);
  (2) change received response before passing it to a spider;
  (3) send a new Request instead of passing received response to a spider;
  (4) pass response to a spider without fetching a web page;
  (5) silently drop some requests.

6、爬虫中间件(Spider Middlewares)
位于EGINE和SPIDERS之间,主要工作是处理SPIDERS的输入(即responses)和输出(即requests)
'''

1、pip3 install wheel
2、pip3 install lxml
3、pip3 install pyopenssl

二 安装
#Windows平台
1、pip3 install wheel #安装后,便支持通过wheel文件安装软件,wheel文件官网:https://www.lfd.uci.edu/~gohlke/pythonlibs
2、pip3 install lxml
3、pip3 install pyopenssl # pyopenssl是一个封装了openssl的python模块。使用它可以方便地进行一些加解密操作。
# pywin32与python3有不兼容的问题,在 下载与当前python相兼容的版本,使用pip install 路径名(.wheel)文件方式进行安装
4、下载并安装pywin32:https://sourceforge.net/projects/pywin32/files/pywin32/ # 去220目录下根据你的系统与python解释器下载相应的版本
# 直接使用国内源下载
pip3 --no-cache-dir install -i https://mirrors.aliyun.com/pypi/simple/pypiwin32 --ignore-installed
# 因为scrapy是基于twisted开发的,所以需要下载twisted
5、下载twisted的wheel文件:http://www.lfd.uci.edu/~gohlke/pythonlibs/#twisted
6、执行pip3 install 下载目录Twisted-17.9.0-cp36-cp36m-win_amd64.whl # 安装本地的twisted文件
   # cmd: >> pip3 install D: ank_filesTwisted-18.9.0-cp36-cp36m-win_amd64.whl
7、pip3 install scrapy # 把1-6做完以后再下载scarpy框架,否则会报错

**Scrapy使用**
1、进入终端cmd
-scrapy
C:Users沈金金>scrapy
Scrapy 1.6.0 - no active project

2、创建scrapy项目
1、创建一个文件夹,专门用于存放scrapy项目
-D:Scrapy_project
2、cmd终端输入
-scrapy startproject Spider Project



二、微信机器人
 1 # from wxpy import *
 2 # bot = Bot()
 3 # bot = Bot(cache_path=True) # 必须先登录过一次以后才可以使用缓存
 4 
 5 
 6 # from wxpy import Bot
 7 # from pyecharts import Pie
 8 # import webbrowser
 9 #
10 # # 实例化一个微信机器人对象
11 # bot = Bot()
12 #
13 # # 获取到微信的所有好友
14 # friends = bot.friends()
15 #
16 # # 设定男性女性位置性别好友名称
17 # attr = ['男朋友', '女朋友', '人妖']
18 #
19 # # 初始化对应好友数量
20 # value = [0, 0, 0]
21 #
22 # # 遍历所有的好友,判断这个好友是男性还是女性
23 # for friend in friends:
24 #     if friend.sex == 1:
25 #         value[0] += 1
26 #     elif friend.sex == 2:
27 #         value[1] += 1
28 #     else:
29 #         value[2] += 1
30 #
31 # # 实例化一个饼状图对象
32 # pie = Pie('tank的好友们!')
33 #
34 # # 图表名称str,属性名称list,属性所对应的值list,is_label_show是否现在标签
35 # pie.add('', attr, value, is_label_show=True)
36 #
37 # # 生成一个html文件
38 # pie.render('friends.html')
39 #
40 # # 打开html文件
41 # webbrowser.open('friends.html')
42 
43 
44 '''
45 $ pip36 install echarts-countries-pypkg
46 $ pip36 install echarts-china-provinces-pypkg
47 $ pip36 install echarts-china-cities-pypkg
48 $ pip36 install echarts-china-counties-pypkg
49 $ pip36 install echarts-china-misc-pypkg
50 '''
51 
52 
53 from wxpy import *
54 from pyecharts import Map
55 import webbrowser
56 bot=Bot(cache_path=True)
57 
58 friends=bot.friends()
59 
60 
61 area_dic={}#定义一个字典,用来存放省市以及省市人数
62 for friend in friends:
63     if friend.province not in area_dic:
64         area_dic[friend.province]=1
65     else:
66         area_dic[friend.province]+=1
67 
68 attr = area_dic.keys()
69 value = area_dic.values()
70 
71 
72 
73 map = Map("好朋友们的地域分布", width=1200, height=600)
74 map.add(
75     "好友地域分布",
76     attr,
77     value,
78     maptype='china',
79     is_visualmap=True, #结合体VisualMap
80 
81 )
82 #is_visualmap -> bool 是否使用视觉映射组件
83 #
84 map.render('area.html')
85 
86 
87 webbrowser.open("area.html")

三、Scrapy爬虫框架

 1 # main()
 2 from scrapy.cmdline import execute
 3 
 4 # 写终端的命令
 5 # scrapy crawl baidu
 6 # 执行baidu爬虫程序
 7 # execute(["scrapy", 'crawl', "baidu"])
 8 
 9 # 创建爬取链家网爬虫程序
10 # execute(["scrapy", "genspider", "lianjia", "lianjia.com"])
11 
12 # 执行链家爬虫程序
13 # execute("scrapy crawl lianjia".split(" "))
14 
15 # --nolog去除日志
16 execute("scrapy crawl --nolog lianjia".split(" "))
 1 # -*- coding: utf-8 -*-
 2 import scrapy
 3 from scrapy import Request
 4 
 5 # response的类
 6 from scrapy.http.response.html import HtmlResponse
 7 class LianjiaSpider(scrapy.Spider):
 8     name = 'lianjia'  # 爬虫程序名
 9     # 只保留包含lianjia.com的url
10     allowed_domains = ['lianjia.com']  # 限制域名
11 
12     # 存放初始请求url
13     start_urls = ['https://bj.lianjia.com/ershoufang/']
14 
15     def parse(self, response):  # response返回的响应对象
16         # print(response)
17         # print(type(response))
18         # # 获取文本
19         # print(response.text)
20         # print(response.url)
21         # 获取区域列表url
22         area_list = response.xpath('//div[@data-role="ershoufang"]/div/a')
23 
24         # 遍历所有区域列表
25         for area in area_list:
26             print(area)
27             '''
28             .extract()提取多个
29             .extract_first()提取一个
30             '''
31             # 1、区域名称
32             area_name = area.xpath('./text()').extract_first()
33             print(area_name)
34             # 2、区域二级url
35             area_url = 'https://bj.lianjia.com/' + area.xpath('./@href').extract_first()
36             print(area_url)
37             # 会把area_url的请求响应数据交给callback方法
38             # yield后面跟着的都会添加到生成器中
39             yield Request(url=area_url, callback=self.parse_area)
40 
41 
42     def parse_area(self, response):
43         # print(response)
44 
45         house_list = response.xpath('//ul[@class="sellListContent"]')
46         # print(house_list)
47         if house_list:
48             for house in house_list:
49 
50                 house_name = house.xpath('.//div[@class="title"]/a/text()').extract_first()
51                 print(house_name)
52 
53                 house_cost = house.xpath('.//div[@class="totalPrice]/text()').extract_first() + ''
54                 print(house_cost)
55 
56                 house_price = house.xpath('.//div[@class="unitPrice"]/span/text()').extract_first()
57                 print(house_price)
58 
59                 pass

原文地址:https://www.cnblogs.com/shendongnian/p/11067117.html