微信网站建设公司,做众筹网站,包装设计模板,网站单页面制作本人为一名刚开始学Python爬虫的小白#xff0c;开贴仅为记录下自己的学习历程#xff0c;方便做review要爬取链接#xff1a;http://tuan.bookschina.com/要爬取内容#xff1a; 图书名称#xff0c; 图书价格#xff0c; 以及对应预览图的link本文用到py packages: req…本人为一名刚开始学Python爬虫的小白开贴仅为记录下自己的学习历程方便做review要爬取链接http://tuan.bookschina.com/要爬取内容 图书名称 图书价格 以及对应预览图的link本文用到py packages: requests, BeautifulSoup, json, cvs打开中国图书网团购页面时发现网站的信息是动态加载的Anyways,先不考虑加载更多页的图书信息我们从尝试着抓取第一页的图书信息开始本次爬虫所用的浏览器为chrome所以我们打开浏览器的开发者模式F12可以看到页面加载的相应信息为了实现模拟浏览器登录功能我们需要查看header的信息完成对应的代码header {‘User-Agent‘: ‘Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36‘,‘Host‘: ‘tuan.bookschina.com‘,‘Referer‘: ‘http://tuan.bookschina.com/‘,‘Accept‘: ‘text/html,application/xhtmlxml,application/xml;q0.9,image/webp,image/apng,*/*;q0.8‘,‘Accept-Encoding‘: ‘gzip, deflate‘,‘Accept-Language‘: ‘zh-CN,zh;q0.9‘}接下来我们需要做的就是分析整个中国图书网的DOM去查看我们需要的信息都封装在哪些tags里面经过地毯式搜索。。。。我们发现我们所需要的信息都封装在 的子节点li里面所以我们打算采取BeautifulSoup的解析抓取功能来实现拿到li内的我们需要的信息对应的代码:url ‘http://tuan.bookschina.com/‘response requests.get(url, headers header) #模仿浏览器登录response.encoding ‘utf-8‘soup BeautifulSoup(response.text,‘html.parser‘)for item in soup.select(‘div .taoListInner ul li‘):print(item.select(‘h2‘)[0].text) #返回对象为数组print(item.select(‘.salePrice‘)[0].text)print(item.select(‘img‘)[0].get(‘src‘)) #get方法用来取得tab内部的属性值首先我们需要调用requests的get方法拿到响应的response然后通过BS进行解析我们会发现在class 名为 taoListInner的div标签中封装了我们想要的ul下的li查看了beautifulsoup的文档对比了find_all 和select决定调用select方法拿到对应的标签然后拿到对应h2标签下的书名 salePrice class下的价格 以及img标签内src的预览图link。这样就可以打印出我们想要的第一页所显示的书籍的信息了。但是问题就出来了。。。如果我们想拿后续页面的更多书籍信息该怎么办呢因为bs的select方法是只能解析静态的Dom的所以我们怀疑后续的图书数据是通过Ajax 或者 JS 加载的我们来到开发者模式的XHR下面我们会发现每当我们下拉滚动条刷新图书信息的时候会跟随者刷新出一个GroupList?.....的链接我们打开他惊喜的发现在previews里封装了我们需要的数据并且是以Json形式予以保存的所以我们要拿到这个Json数据需要去拿他的Request URL当前的URL为http://tuan.bookschina.com/Home/GroupList?Type0Category0Price0Order11Page2Tyjsontrue我们会发现一个规律每当有新的书籍信息刷新一次的时候URL中的Page也会跟随递增所以问题迎刃而解了。。。。我们只需要去通过URL拿到返回的JSON进行解析便可以拿到我们想要的全部数据了也验证了一个说法许多动态加载的网站都会把Json数据封装作为response这样就给我们的爬虫找到一条捷径url ‘http://tuan.bookschina.com/Home/GroupList?Type0Category0Price0Order11Page2Tyjsontrue‘response requests.get(url)result json.loads(response.text)bookinfo {}for data in result[‘Data‘]:bookinfo[‘bookName‘] data[‘book_name‘]bookinfo[‘price‘] data[‘group_price‘]bookinfo[‘iconLink‘] data[‘group_image‘]print(url)这里用里调用了loads()方法把返回的json数据转换为python的字典方便拿数据拿到数据后我们决定把数据存入磁盘生成cvs的excel文件方便做进一步的数据分析所以本次爬虫小实验全部代码如下import requestsfrom bs4 import BeautifulSoupimport jsonimport csvdef parse_one_page():header {‘User-Agent‘: ‘Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36‘,‘Host‘: ‘tuan.bookschina.com‘,‘Referer‘: ‘http://tuan.bookschina.com/‘,‘Accept‘: ‘text/html,application/xhtmlxml,application/xml;q0.9,image/webp,image/apng,*/*;q0.8‘,‘Accept-Encoding‘: ‘gzip, deflate‘,‘Accept-Language‘: ‘zh-CN,zh;q0.9‘}url ‘http://tuan.bookschina.com/‘response requests.get(url, headers header) #模仿浏览器登录response.encoding ‘utf-8‘soup BeautifulSoup(response.text,‘html.parser‘)for item in soup.select(‘div .taoListInner ul li‘):print(item.select(‘h2‘)[0].text) #返回对象为数组print(item.select(‘.salePrice‘)[0].text)print(item.select(‘img‘)[0].get(‘src‘)) #get方法用来取得tab内部的属性值def dynamtic_claw_data(page, headers, fileName):for i in range(page):url ‘http://tuan.bookschina.com/Home/GroupList?Type0Category0Price0Order11Page‘ str(i) ‘Tyjsontrue‘response requests.get(url)result json.loads(response.text)bookinfo {}for data in result[‘Data‘]:bookinfo[‘bookName‘] data[‘book_name‘]bookinfo[‘price‘] data[‘group_price‘]bookinfo[‘iconLink‘] data[‘group_image‘]write_csv_rows(fileName,headers,bookinfo)print(url)def write_csv_headers(path, headers):with open(path, ‘a‘, encoding‘gb18030‘, newline‘‘) as f:f_csv csv.DictWriter(f, headers)f_csv.writeheader()def write_csv_rows(path, headers, rows):with open(path, ‘a‘, encoding‘gb18030‘, newline‘‘) as f:f_csv csv.DictWriter(f, headers)# 如果写入数据为字典则写入一行否则写入多行if type(rows) type({}):f_csv.writerow(rows)else:f_csv.writerows(rows)def main(page):# parse_one_page() #Tip: beautifulSoup testcsv_filename bookInfo.csvheaders [‘bookName‘, ‘price‘, ‘iconLink‘]write_csv_headers(csv_filename,headers)dynamtic_claw_data(page, headers, csv_filename)if __name__ ‘__main__‘:main(20) #input page num to start原文https://www.cnblogs.com/ChrisInsistPy/p/8981820.html