'''
主页:
图标地址、
https://www.wandoujia.com/category/6001
32
'''
import requests
from bs4 import BeautifulSoup
from pymongo import MongoClient
# 连接MongoDB客户端
client = MongoClient('localhost', 27017)
# 创建或选择wangdoujia库,index集合
index_col = client['wangdoujia']['index']
# 创建或选择wangdoujia库,detail集合
detail_col = client['wangdoujia']['detail']
# 1、发送请求
def get_page(url):
response = requests.get(url)
return response
# 2、开始解析
# 解析详情页
def parse_detail(text):
soup = BeautifulSoup(text, 'lxml')
# print(soup)
try:
name = soup.find(name="span", attrs={"class": "title"}).text
except Exception:
name = None
try:
love = soup.find(name='span', attrs={"class": "love"}).text
except Exception:
love = None
try:
commit_num = soup.find(name='a', attrs={"class": "comment-open"}).text
except Exception:
commit_num = None
try:
commit_content = soup.find(name='div', attrs={"class": "con"}).text
except Exception:
commit_content = None
try:
download_url = soup.find(name='a', attrs={"class": "normal-dl-btn"}).attrs['href']
except Exception:
# 若有异常,设置为None
download_url = None
if name and love and commit_num and commit_content and download_url:
detail_data = {
'name': name,
'love': love,
'commit_num': commit_num,
'download_url':download_url
}
if not love:
detail_data = {
'name': name,
'love': '没有点赞',
'commit_num': commit_num,
'download_url': download_url
}
if not download_url:
detail_data = {
'name': name,
'love': love,
'commit_num': commit_num,
'download_url':'没有安装包'
}
detail_col.insert(detail_data)
print(f'{name}app数据插入成功!')
# 解析主页
def parse_index(data):
soup = BeautifulSoup(data, 'lxml')
# 获取所有app的li标签
app_list = soup.find_all(name='li', attrs={"class": "card"})
for app in app_list:
# print('*' * 1000)
# print(app)
# 图标地址
# 获第一个img标签中的data-origina属性
img = app.find(name='img').attrs['data-original']
# print(img)
# 下载次数
# 获取class为install-count的span标签中的文本
down_num = app.find(name='span',attrs={"class": "install-count"}).text
# print(down_num)
# 大小
# 根据文本正则获取到文本中包含 数字 + MB (\d+代表数字)的span标签中的文本
import re
size = soup.find(name='span', text=re.compile("\d+MB")).text
# print(size)
# 详情页地址
# 获取class为detail-check-btn的a标签中的href属性
detail_url = app.find(name='a').attrs['href']
# print(detail_url)
# 拼接数据
index_data = {
'img':img,
'down_num':down_num,
'size': size,
'detail_url': detail_url
}
index_col.insert(index_data)
print(f'主页数据插入成功')
# 3、往app详情页发送请求
response = get_page(detail_url)
# print(response.text)
# print('tank')
# 4、解析详情页
parse_detail(response.text)
def main():
for line in range(1,33):
url = f'https://www.wandoujia.com/wdjweb/api/category/more?catId=6001&subCatId=0&page={line}&ctoken=ql8VkarJqaE7VAYNAEe2JueZ'
# 1、往app接口发送前请求
response = get_page(url)
# print(response.text)
print('*' * 1000)
# 反序列化为字典
data = response.json()
# 获取接口中app标签数据
app_li = data['data']['content']
# print(app_li)
# 2、解析app标签数据
parse_index(app_li)
# 执行完所有函数关闭mongoDB客户端
client.close()
if __name__ == '__main__':
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:\tank_files\Twisted-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
# from wxpy import *
# bot = Bot()
# bot = Bot(cache_path=True) # 必须先登录过一次以后才可以使用缓存
# from wxpy import Bot
# from pyecharts import Pie
# import webbrowser
#
# # 实例化一个微信机器人对象
# bot = Bot()
#
# # 获取到微信的所有好友
# friends = bot.friends()
#
# # 设定男性\女性\位置性别好友名称
# attr = ['男朋友', '女朋友', '人妖']
#
# # 初始化对应好友数量
# value = [0, 0, 0]
#
# # 遍历所有的好友,判断这个好友是男性还是女性
# for friend in friends:
# if friend.sex == 1:
# value[0] += 1
# elif friend.sex == 2:
# value[1] += 1
# else:
# value[2] += 1
#
# # 实例化一个饼状图对象
# pie = Pie('tank的好友们!')
#
# # 图表名称str,属性名称list,属性所对应的值list,is_label_show是否现在标签
# pie.add('', attr, value, is_label_show=True)
#
# # 生成一个html文件
# pie.render('friends.html')
#
# # 打开html文件
# webbrowser.open('friends.html')
'''
$ pip36 install echarts-countries-pypkg
$ pip36 install echarts-china-provinces-pypkg
$ pip36 install echarts-china-cities-pypkg
$ pip36 install echarts-china-counties-pypkg
$ pip36 install echarts-china-misc-pypkg
'''
from wxpy import *
from pyecharts import Map
import webbrowser
bot=Bot(cache_path=True)
friends=bot.friends()
area_dic={}#定义一个字典,用来存放省市以及省市人数
for friend in friends:
if friend.province not in area_dic:
area_dic[friend.province]=1
else:
area_dic[friend.province]+=1
attr = area_dic.keys()
value = area_dic.values()
map = Map("好朋友们的地域分布", width=1200, height=600)
map.add(
"好友地域分布",
attr,
value,
maptype='china',
is_visualmap=True, #结合体VisualMap
)
#is_visualmap -> bool 是否使用视觉映射组件
#
map.render('area.html')
webbrowser.open("area.html")
# main()
from scrapy.cmdline import execute
# 写终端的命令
# scrapy crawl baidu
# 执行baidu爬虫程序
# execute(["scrapy", 'crawl', "baidu"])
# 创建爬取链家网爬虫程序
# execute(["scrapy", "genspider", "lianjia", "lianjia.com"])
# 执行链家爬虫程序
# execute("scrapy crawl lianjia".split(" "))
# --nolog去除日志
execute("scrapy crawl --nolog lianjia".split(" "))
# -*- coding: utf-8 -*-
import scrapy
from scrapy import Request
# response的类
from scrapy.http.response.html import HtmlResponse
class LianjiaSpider(scrapy.Spider):
name = 'lianjia' # 爬虫程序名
# 只保留包含lianjia.com的url
allowed_domains = ['lianjia.com'] # 限制域名
# 存放初始请求url
start_urls = ['https://bj.lianjia.com/ershoufang/']
def parse(self, response): # response返回的响应对象
# print(response)
# print(type(response))
# # 获取文本
# print(response.text)
# print(response.url)
# 获取区域列表url
area_list = response.xpath('//div[@data-role="ershoufang"]/div/a')
# 遍历所有区域列表
for area in area_list:
print(area)
'''
.extract()提取多个
.extract_first()提取一个
'''
# 1、区域名称
area_name = area.xpath('./text()').extract_first()
print(area_name)
# 2、区域二级url
area_url = 'https://bj.lianjia.com/' + area.xpath('./@href').extract_first()
print(area_url)
# 会把area_url的请求响应数据交给callback方法
# yield后面跟着的都会添加到生成器中
yield Request(url=area_url, callback=self.parse_area)
def parse_area(self, response):
# print(response)
house_list = response.xpath('//ul[@class="sellListContent"]')
# print(house_list)
if house_list:
for house in house_list:
house_name = house.xpath('.//div[@class="title"]/a/text()').extract_first()
print(house_name)
house_cost = house.xpath('.//div[@class="totalPrice]/text()').extract_first() + '万'
print(house_cost)
house_price = house.xpath('.//div[@class="unitPrice"]/span/text()').extract_first()
print(house_price)
pass