一.昨日作业 ![]() 1 import requests 2 from bs4 import BeautifulSoup 3 from pymongo import MongoClient 4 5 # 连接MongoDB客户端 6 client = MongoClient('localhost', 27017) 7 # 创建或选择wangdoujia库,index集合 8 index_col = client['wangdoujia']['index'] 9 # 创建或选择wangdoujia库,detail集合 10 detail_col = client['wangdoujia']['detail'] 11 12 # 1、发送请求 13 def get_page(url): 14 response = requests.get(url) 15 return response 16 17 # 2、开始解析 18 # 解析详情页 19 def parse_detail(text): 20 21 soup = BeautifulSoup(text, 'lxml') 22 # print(soup) 23 24 try: 25 name = soup.find(name="span", attrs={"class": "title"}).text 26 except Exception: 27 name = None 28 29 30 31 try: 32 love = soup.find(name='span', attrs={"class": "love"}).text 33 except Exception: 34 love = None 35 36 37 38 try: 39 commit_num = soup.find(name='a', attrs={"class": "comment-open"}).text 40 except Exception: 41 commit_num = None 42 43 44 try: 45 commit_content = soup.find(name='div', attrs={"class": "con"}).text 46 except Exception: 47 commit_content = None 48 49 50 try: 51 download_url = soup.find(name='a', attrs={"class": "normal-dl-btn"}).attrs['href'] 52 except Exception: 53 # 若有异常,设置为None 54 download_url = None 55 56 57 if name and love and commit_num and commit_content and download_url: 58 detail_data = { 59 'name': name, 60 'love': love, 61 'commit_num': commit_num, 62 'download_url':download_url 63 } 64 65 if not love: 66 detail_data = { 67 'name': name, 68 'love': '没有点赞', 69 'commit_num': commit_num, 70 'download_url': download_url 71 } 72 if not download_url: 73 detail_data = { 74 'name': name, 75 'love': love, 76 'commit_num': commit_num, 77 'download_url':'没有安装包' 78 } 79 80 81 detail_col.insert(detail_data) 82 print(f'{name}app数据插入成功!') 83 84 # 解析主页 85 def parse_index(data): 86 soup = BeautifulSoup(data, 'lxml') 87 88 # 获取所有app的li标签 89 app_list = soup.find_all(name='li', attrs={"class": "card"}) 90 for app in app_list: 91 # print('*' * 1000) 92 # print(app) 93 # 图标地址 94 # 获第一个img标签中的data-origina属性 95 img = app.find(name='img').attrs['data-original'] 96 # print(img) 97 98 # 下载次数 99 # 获取class为install-count的span标签中的文本 100 down_num = app.find(name='span',attrs={"class": "install-count"}).text 101 # print(down_num) 102 103 # 大小 104 # 根据文本正则获取到文本中包含 数字 MB (\d 代表数字)的span标签中的文本 105 import re 106 size = soup.find(name='span', text=re.compile("\d MB")).text 107 # print(size) 108 109 # 详情页地址 110 # 获取class为detail-check-btn的a标签中的href属性 111 detail_url = app.find(name='a').attrs['href'] 112 # print(detail_url) 113 114 # 拼接数据 115 index_data = { 116 'img':img, 117 'down_num':down_num, 118 'size': size, 119 'detail_url': detail_url 120 } 121 122 index_col.insert(index_data) 123 print(f'主页数据插入成功') 124 125 # 3、往app详情页发送请求 126 response = get_page(detail_url) 127 # print(response.text) 128 # print('tank') 129 130 # 4、解析详情页 131 parse_detail(response.text) 132 133 134 def main(): 135 for line in range(1,33): 136 url = f'https://www.wandoujia.com/wdjweb/api/category/more?catId=6001&subCatId=0&page={line}&ctoken=ql8VkarJqaE7VAYNAEe2JueZ' 137 138 # 1、往app接口发送前请求 139 response = get_page(url) 140 # print(response.text) 141 print('*' * 1000) 142 # 反序列化为字典 143 data = response.json() 144 # 获取接口中app标签数据 145 app_li = data['data']['content'] 146 # print(app_li) 147 # 2、解析app标签数据 148 parse_index(app_li) 149 150 # 执行完所有函数关闭mongoDB客户端 151 client.close() 152 153 154 if __name__ == '__main__': 155 main()View Code 二.scrapy爬虫框架的使用 ? ? Scrapy爬虫框架:发送请求 ---> 获取响应数据 ---> 解析数据 ---> 保存数据 ? ? ** Scarpy框架介绍 ** ? ? 1、引擎(EGINE) ? ? 2、调度器(SCHEDULER) ? ?? 同时去除重复的网址 ? ? 3、下载器(DOWLOADER) ? ?? 4、爬虫(SPIDERS) ? ?? 5、项目管道(ITEM PIPLINES) ? ? ? ?? 位于Scrapy引擎和下载器之间,主要用来处理从EGINE传到DOWLOADER的请求request,已经从DOWNLOADER传到EGINE的响应response, ? ? ? ? 你可用该中间件做以下几件事: ? ? ? 6、爬虫中间件(Spider Middlewares) ? ? ? ** Scarpy安装 ** ? ? ?? 6、pip3 install scrapy ? ? ?? ** Scarpy使用 ** ? ? ?? 2、创建scrapy项目 ? ? ? ? 3.创建爬虫程序 ? ? ? 3、启动scrapy项目,执行爬虫程序 ? ? ? ? ? # 找到爬虫程序文件进行执行 ? ? ? ?? # 根据爬虫名称找到相应的爬虫程序执行 三.微信机器人 ? ?? 安装:wxpy 支持 Python 3.4-3.6,以及 2.7 版本? ? ? ? ? ? ? ? pip3 install -U wxpy ? ?? 安装 pillow模块 ? ? ? ? ? ? ? pip3 install pillow ? ?? 安装 pyecharts模块 ? ? ? ? ? ? ? pip3 install pyecharts ? ![]() 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")View Code 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", ""]) 11 12 # 执行链家爬虫程序 13 # execute("scrapy crawl lianjia".split(" ")) 14 15 # --nolog去除日志 16 execute("scrapy crawl --nolog lianjia".split(" ")) ![]() 1 import scrapy 2 from scrapy import Request 3 4 # response的类 5 from scrapy.http.response.html import HtmlResponse 6 class LianjiaSpider(scrapy.Spider): 7 name = 'lianjia' # 爬虫程序名 8 # 只保留包含的url 9 allowed_domains = [''] # 限制域名 10 11 # 存放初始请求url 12 start_urls = ['https://bj./ershoufang/'] 13 14 def parse(self, response): # response返回的响应对象 15 # print(response) 16 # print(type(response)) 17 # # 获取文本 18 # print(response.text) 19 # print(response.url) 20 # 获取区域列表url 21 area_list = response.xpath('//div[@data-role="ershoufang"]/div/a') 22 23 # 遍历所有区域列表 24 for area in area_list: 25 print(area) 26 ''' 27 .extract()提取多个 28 .extract_first()提取一个 29 ''' 30 # 1、区域名称 31 area_name = area.xpath('./text()').extract_first() 32 print(area_name) 33 # 2、区域二级url 34 area_url = 'https://bj./' area.xpath('./@href').extract_first() 35 print(area_url) 36 # 会把area_url的请求响应数据交给callback方法 37 # yield后面跟着的都会添加到生成器中 38 yield Request(url=area_url, callback=self.parse_area) 39 40 41 def parse_area(self, response): 42 # print(response) 43 44 house_list = response.xpath('//ul[@class="sellListContent"]') 45 # print(house_list) 46 if house_list: 47 for house in house_list: 48 49 house_name = house.xpath('.//div[@class="title"]/a/text()').extract_first() 50 print(house_name) 51 52 house_cost = house.xpath('.//div[@class="totalPrice]/text()').extract_first() '万' 53 print(house_cost) 54 55 house_price = house.xpath('.//div[@class="unitPrice"]/span/text()').extract_first() 56 print(house_price) 57 58 passView Code ? 来源:https://www./content-1-258101.html |
|