爬取中国红娘网数据(精简版)
一、爬取过程分析
1、引入requests库,获取网页源代码:
2、引入BeautifulSoup库,解析网页源代码并获取所需数据:
3、利用for循环函数获取网页1页数据:
4、利用for循环函数获取网页10页数据(获取页数只需变更for循环次数即可):
5、引入pandas库,创建存储数据列表并将爬取网页数据在存储列表中输出:6、引入openpyxl库,将爬取网页数据保存至excel表中(import os—os.getcwd()用于查看数据保存位置):
2、爬取函数汇总
上代码:
#主函数
import requests
from bs4 import BeautifulSoup
import pandas as pd
import openpyxl
#定义存储变量
nianling=[]
diqu=[]
hunyin=[]
shengao=[]
jieshao=[]
#获取网页源代码的函数
for i in range(6071):
url='http://www.hongniang.com/match?&page'+str(i)
request=requests.get(url)
html=request.text
#解析源代码,提取信息
soup=BeautifulSoup(html,'html.parser')
for info in soup.find_all('li',class_='pin'):
nianling.append(info.find_all('span')[1].text)
diqu.append(info.find_all('span')[2].text)
hunyin.append(info.find_all('span')[3].text)
shengao.append(info.find_all('span')[4].text)
jieshao.append(info.find_all('div',class_='db')[0].text.replace('\t','').replace('\r','').replace('\n','').replace(' ','')[5:])
pd.DataFrame({'年龄':nianling,'地区':diqu,'婚姻状况':hunyin,'身高':shengao,'介绍':jieshao})
data=pd.DataFrame({'年龄':nianling,'地区':diqu,'婚姻状况':hunyin,'身高':shengao,'介绍':jieshao})
writer=pd.ExcelWriter('data.xlsx')
data.to_excel(writer,'爬虫数据')
writer.save()