用requests和bs做个简单的爬取网DAI之家的例子。

只做笔记用。


#!/usr/bin/python3

import requests
from bs4 import BeautifulSoup
import re
import xlwt class wdzj_spider:
pingTaiInfo = [] def request(self, url):
headers = {'User-Agent': "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/22.0.1207.1 Safari/537.1"}
return requests.get(url, headers=headers) def saveToExcel(self, infoList, fileName='resultme.xls', sheetName='www.wdzj.com'): # 对于要写入的每一个元素,先找他的title在哪列,写入到对应的列去
rowNo = 1
excelTitle = {} book = xlwt.Workbook() # 打开一个excel
if book is None:
print("创建文件{0}失败".format(fileName))
return None
sheet = book.add_sheet(sheetName) # 根据顺序获取sheet
if sheet is None:
print("创建表单{0}失败".format(sheetName))
return None for info in infoList:
for item in info.items():
if str(item[0]) in excelTitle:
colNo = excelTitle[item[0]]
else:
colNo = len(excelTitle)
excelTitle[str(item[0])] = colNo
sheet.write(rowNo, colNo, str(item[1]))
rowNo = rowNo + 1
for m in excelTitle.items():
sheet.write(0, m[1], m[0])
book.save(fileName)
return rowNo def getDataplaneFromPage(self, Link):
mainHtml = self.request(Link)
dataInfo = {}
#默认编码有问题,需手动转码
txtUTF8 = str(mainHtml.content, 'utf-8')
mainBS = BeautifulSoup(txtUTF8, "lxml",from_encoding="utf8")
lis = mainBS.find_all('li', attrs={'class':'normal'})
for tr in lis:
divs = tr.find_all('div')
dataInfo[divs[1].text.strip()] = divs[0].text.strip()
# print("数据={0}".format(dataInfo))
return dataInfo def getGongshangFromPage(self, Link):
mainHtml = self.request(Link)
gongshangInfo = {}
#默认编码有问题,需手动转码
txtUTF8 = str(mainHtml.content, 'utf-8')
mainBS = BeautifulSoup(txtUTF8, "lxml",from_encoding="utf8")
trs = mainBS.find('div', attrs={'class':'lcen'}).find_all('tr')
for tr in trs:
tdTitles = tr.find_all('td', attrs={'class':'t'})
tds = tr.find_all('td')
index = 1
for td in tdTitles:
gongshangInfo[td.text] = tds[index].text.strip(' \n\r')
index = index + 2
# print("工商信息={0}".format(gongshangInfo))
return gongshangInfo def getLinkFromPage(self, pingtaiName, pingtaiLink):
shujuInfo = {}
lianxifangshiInfo = {}
pingtaiHtml = self.request(pingtaiLink)
#默认编码有问题,需手动转码
txtUTF8 = str(pingtaiHtml.content, 'utf-8')
mainBS = BeautifulSoup(txtUTF8, "lxml",from_encoding="utf8")
briefText = mainBS.find("div", class_="cen-zk").get_text().strip(' \n\r')
briefInfo={"P2P平台名称":pingtaiName, "简介":briefText}
# print("简介={0}".format(briefText))
gongshangLink = 'https://'+mainBS.find('a', text='工商/备案')['href'].lstrip('/')
dataA = mainBS.find('div', attrs={'class':'common-header-nav'}).find('a', text='数据') lianxifangshiTitles =mainBS.find('div', attrs={'class':"da-lxfs zzfwbox"}).find_all('div', class_='l')
lianxifangshiContents = mainBS.find('div', attrs={'class': "da-lxfs zzfwbox"}).find_all('div', class_='r') for i in range(0, len(lianxifangshiTitles)):
lianxifangshiInfo[lianxifangshiTitles[i].get_text().strip(' \n\r')] = lianxifangshiContents[i].get_text().strip(' \n\r')
# print("联系方式={0}".format(lianxifangshiInfo)) if dataA:
dataLink = 'https://' + dataA['href'].lstrip('/')
shujuInfo = self.getDataplaneFromPage(dataLink) gongshangInfo = self.getGongshangFromPage(gongshangLink)
self.pingTaiInfo.append({**briefInfo, **gongshangInfo, **shujuInfo, **lianxifangshiInfo}) def getAllPage(self):
startUrl = 'https://www.wdzj.com/dangan/search?filter=&sort=1&currentPage=1'
mainHtml = self.request(startUrl)
pageStr = BeautifulSoup(mainHtml.text, "lxml").find("span", class_="all").text
searchObj = re.search(r'1/([0-9]+)', pageStr, re.M | re.I)
pageCount = searchObj.group(1) startUrl = 'https://www.wdzj.com/dangan/search?filter=&sort=1&currentPage='
baseUrl = 'https://www.wdzj.com' print("总页数:{0}".format(pageCount))
for i in range(1, int(pageCount)+1):
# for i in range(1, 2): urlPage = startUrl + str(i)
pageHtml = self.request(urlPage)
pageStrs = BeautifulSoup(pageHtml.text, "lxml").find('ul',attrs={'class':'terraceList'}).find_all('h2') print("---------------------------------")
print("开始爬取第{0}页,共存在{1}个平台数据".format(i, len(pageStrs)))
for p in pageStrs:
a = p.find('a')
self.getLinkFromPage(a.get_text(), baseUrl+a['href'])
print("#", end='',flush=True)
print("\n结束爬取第{0}页,共爬取{1}个平台数据".format(i,len(pageStrs)))
self.saveToExcel(self.pingTaiInfo,fileName='p2p.xls') if __name__ == '__main__':
w = wdzj_spider()
w.getAllPage()
 

做下修改

 #!/usr/bin/python3

 import requests
from bs4 import BeautifulSoup
import re
import xlwt class wdzj_spider:
pingTaiInfo = []
book=None
sheet=None
excelTitle = {}
rowNo = 1 def request(self, url):
headers = {'User-Agent': "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/22.0.1207.1 Safari/537.1"}
return requests.get(url, headers=headers) def openExcel(self, fileName='resultme.xls',sheetName='www.wdzj.com'):
self.book = xlwt.Workbook() # 打开一个excel
if self.book is None:
print("创建文件{0}失败".format(fileName))
return None
self.sheet = self.book.add_sheet(sheetName) # 根据顺序获取sheet
if self.sheet is None:
print("创建表单{0}失败".format(sheetName))
return None def closeExcel(self, fileName='resultme.xls'):
for m in self.excelTitle.items():
self.sheet.write(0, m[1], m[0])
self.book.save(fileName) def saveToExcel(self, infoList, fileName='resultme.xls'):
# 对于要写入的每一个元素,先找他的title在哪列,写入到对应的列去
for info in infoList:
for item in info.items():
if str(item[0]) in self.excelTitle:
colNo = self.excelTitle[item[0]]
else:
colNo = len(self.excelTitle)
self.excelTitle[str(item[0])] = colNo
self.sheet.write(self.rowNo, colNo, str(item[1]))
self.rowNo = self.rowNo + 1
self.book.save(fileName)
return self.rowNo def getDataplaneFromPage(self, Link):
mainHtml = self.request(Link)
dataInfo = {}
#默认编码有问题,需手动转码
txtUTF8 = str(mainHtml.content, 'utf-8')
mainBS = BeautifulSoup(txtUTF8, "lxml",from_encoding="utf8")
lis = mainBS.find_all('li', attrs={'class':'normal'})
for tr in lis:
divs = tr.find_all('div')
dataInfo[divs[1].text.strip()] = divs[0].text.strip()
# print("数据={0}".format(dataInfo))
return dataInfo def getGongshangFromPage(self, Link):
mainHtml = self.request(Link)
gongshangInfo = {}
#默认编码有问题,需手动转码
txtUTF8 = str(mainHtml.content, 'utf-8')
mainBS = BeautifulSoup(txtUTF8, "lxml",from_encoding="utf8")
trs = mainBS.find('div', attrs={'class':'lcen'}).find_all('tr')
for tr in trs:
tdTitles = tr.find_all('td', attrs={'class':'t'})
tds = tr.find_all('td')
index = 1
for td in tdTitles:
gongshangInfo[td.text] = tds[index].text.strip(' \n\r')
index = index + 2
# print("工商信息={0}".format(gongshangInfo))
return gongshangInfo def getLinkFromPage(self, pingtaiName, pingtaiLink):
shujuInfo = {}
lianxifangshiInfo = {}
pingtaiHtml = self.request(pingtaiLink)
#默认编码有问题,需手动转码
txtUTF8 = str(pingtaiHtml.content, 'utf-8')
mainBS = BeautifulSoup(txtUTF8, "lxml",from_encoding="utf8")
briefText = mainBS.find("div", class_="cen-zk").get_text().strip(' \n\r')
briefInfo={"P2P平台名称":pingtaiName, "简介":briefText}
# print("简介={0}".format(briefInfo))
gongshangLink = 'https://'+mainBS.find('a', text='工商/备案')['href'].lstrip('/')
dataA = mainBS.find('div', attrs={'class':'common-header-nav'}).find('a', text='数据') lianxifangshiBox = mainBS.find('div', attrs={'class':"da-lxfs zzfwbox"})
lianxifangshiTitles=[]
lianxifangshiContents=[]
if lianxifangshiBox:
lianxifangshiTitles =lianxifangshiBox.find_all('div', class_='l')
lianxifangshiContents = lianxifangshiBox.find_all('div', class_='r') for i in range(0, len(lianxifangshiTitles)):
lianxifangshiInfo[lianxifangshiTitles[i].get_text().strip(' \n\r')] = lianxifangshiContents[i].get_text().strip(' \n\r')
# print("联系方式={0}".format(lianxifangshiInfo)) if dataA:
dataLink = 'https://' + dataA['href'].lstrip('/')
shujuInfo = self.getDataplaneFromPage(dataLink) gongshangInfo = self.getGongshangFromPage(gongshangLink)
self.pingTaiInfo.append({**briefInfo, **gongshangInfo, **shujuInfo, **lianxifangshiInfo}) def getAllPage(self):
startUrl = 'https://www.wdzj.com/dangan/search?filter=&sort=1&currentPage=1'
mainHtml = self.request(startUrl)
pageStr = BeautifulSoup(mainHtml.text, "lxml").find("span", class_="all").text
searchObj = re.search(r'1/([0-9]+)', pageStr, re.M | re.I)
pageCount = searchObj.group(1) startUrl = 'https://www.wdzj.com/dangan/search?filter=&sort=1&currentPage='
baseUrl = 'https://www.wdzj.com' print("总页数:{0}".format(pageCount))
fileName = 'p2p.xls'
self.openExcel(fileName)
for i in range(1, int(pageCount)+1):
# for i in range(1, 2):
urlPage = startUrl + str(i)
pageHtml = self.request(urlPage)
pageStrs = BeautifulSoup(pageHtml.text, "lxml").find('ul',attrs={'class':'terraceList'}).find_all('h2') print("---------------------------------")
print("开始爬取第{0}页,共存在{1}个平台数据".format(i, len(pageStrs)))
count=0
for p in pageStrs:
a = p.find('a')
try:
self.getLinkFromPage(a.get_text(), baseUrl+a['href'])
count = count + 1
except:
print("爬取第{0}个数据,名称<{1}>失败".format(count+1, a.get_text()))
print("#", end='',flush=True)
print("\n结束爬取第{0}页,共爬取{1}个平台数据".format(i,count))
self.saveToExcel(self.pingTaiInfo, fileName=fileName)
self.pingTaiInfo.clear()
self.closeExcel(fileName) if __name__ == '__main__':
w = wdzj_spider()
w.getAllPage()

网DAI之家简单爬取的更多相关文章

  1. 用BeautifulSoup简单爬取BOSS直聘网岗位

    用BeautifulSoup简单爬取BOSS直聘网岗位 爬取python招聘 import requests from bs4 import BeautifulSoup def fun(path): ...

  2. Golang+chromedp+goquery 简单爬取动态数据

    目录 Golang+chromedp+goquery 简单爬取动态数据 Golang的安装 下载golang软件 解压golang 配置golang 重新导入配置 chromedp框架的使用 实际的代 ...

  3. java爬虫-简单爬取网页图片

    刚刚接触到“爬虫”这个词的时候是在大一,那时候什么都不明白,但知道了百度.谷歌他们的搜索引擎就是个爬虫. 现在大二.再次燃起对爬虫的热爱,查阅资料,知道常用java.python语言编程,这次我选择了 ...

  4. Python简单爬取Amazon图片-其他网站相应修改链接和正则

    简单爬取Amazon图片信息 这是一个简单的模板,如果需要爬取其他网站图片信息,更改URL和正则表达式即可 1 import requests 2 import re 3 import os 4 de ...

  5. 用python爬虫简单爬取 笔趣网:类“起点网”的小说

    首先:文章用到的解析库介绍 BeautifulSoup: Beautiful Soup提供一些简单的.python式的函数用来处理导航.搜索.修改分析树等功能. 它是一个工具箱,通过解析文档为用户提供 ...

  6. 练习: bs4 简单爬取 + matplotlib 折线图显示 (关键词,职位数量、起薪)

    要看一种技术在本地的流行程度,最简单的就是找招聘网站按关键词搜索. 比如今天查到的职位数量是vue 1296个,react 1204个,angular 721个.国际上比较流行的是react,本地市场 ...

  7. python网络爬虫--简单爬取糗事百科

    刚开始学习python爬虫,写了一个简单python程序爬取糗事百科. 具体步骤是这样的:首先查看糗事百科的url:http://www.qiushibaike.com/8hr/page/2/?s=4 ...

  8. 一、python简单爬取静态网页

    一.简单爬虫框架 简单爬虫框架由四个部分组成:URL管理器.网页下载器.网页解析器.调度器,还有应用这一部分,应用主要是NLP配合相关业务. 它的基本逻辑是这样的:给定一个要访问的URL,获取这个ht ...

  9. python scrapy简单爬虫记录(实现简单爬取知乎)

    之前写了个scrapy的学习记录,只是简单的介绍了下scrapy的一些内容,并没有实际的例子,现在开始记录例子 使用的环境是python2.7, scrapy1.2.0 首先创建项目 在要建立项目的目 ...

随机推荐

  1. git bash push 本地的commit到远程 -- ssh keys设置

    1.  检查是否已经创建 ssh keys git bash 下,cd ~/.ssh 如何出现“No such file or directory”,则表示需要创建一个ssh keys. 2. 创建新 ...

  2. 【转载】Sqlserver使用Right函数从最右边向前截取固定长度字符串

    在SQL语句查询过程中,Sqlserver支持使用LEFT().RIGHT().SUBSTRING()等几个函数对字符串进行截取操作,其中Left函数表示从开始字符向后截取多少个字符,Right函数表 ...

  3. React Native 开发豆瓣评分(一)环境搭建&配置模拟器

    详细可参考 官方文档,这里进记录一些重要过程. 安装环境 下载 Android Studio 选择 Custom 进行安装: Android SDK Android SDK Platform Perf ...

  4. 采集代理ip 地址【西刺,快代理】

    # 嗯,...因为经常需要使用代理去抓一点东西,就有了下面一段代码,第一版不是很好,后面用到了再来优化 import re,pymysql,time,redis from urllib.request ...

  5. Dumpsys Alarm查看应用程序唤醒命令

    Dumpsys alarm查看应用程序唤醒命令: 在安卓adb root进如命令行后(没有root或者root群组的权限执行不了该命令), 1. <span style="font-s ...

  6. 记录java+testng运行selenium(三)---xml、ini、excel、日志等配置

    一: ini文件 ini目前只用处存储浏览类型及需要打开的url,ini文件放在configs文件夹下面. 读取ini代码如下: package toolskit.documents; import ...

  7. java - day015 - 手写双向链表, 异常(续), IO(输入输出)

    类的内存分配 加载到方法区 对象在堆内存 局部变量在栈内存 判断真实类型,在方法区加载的类 对象.getClass(); 类名.class; 手写双向链表 package day1501_手写双向链表 ...

  8. SQL进阶17-变量的声明/使用(输出)--全局变量/会话变量--用户变量/局部变量

    /*进阶17 变量 系统变量: 全局变量: 会话变量: 自定义变量: 用户变量: 局部变量: */ /* #一: 系统变量 #说明: 变量由系统提供,不是用户定义的,属于服务器层面 #使用的语法 #1 ...

  9. 分享一个快的飞起的maven的settings.xml文件

    <?xml version="1.0"?> <settings> <localRepository>/home/yizhen/.m2/repos ...

  10. GIL 信号量 event事件 线程queue

    GIL全局解释器锁 官方解释: In CPython, the global interpreter lock, or GIL, is a mutex that prevents multiple n ...