初学,代码有点烂,有些错误先不处理。
#!/usr/bin/python
# -*- coding: <encoding name> -*-
import requests
from bs4 import BeautifulSoup
from openpyxl import Workbook
wb = Workbook()
ws = wb.active
ws.append(['序号','楼盘名称', '面积', '价格','地址'])
# wb.save("e:sample.xlsx")
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36'
}
# 定义楼盘的各项信息列表,便于进行数据追加保存
name_list = []
price_list = []
area_list = []
add_list = []
i = 1
pagenum = input('请输入要抓取<楼盘网>多少页的数据:')
# 通过循环,设定pagenum数值来抓取多少页的楼盘数据
while i <= int(pagenum):
url = 'http://fs.loupan.com/xinfang/p'+str(i)
res = requests.get(url,headers = headers)
print('第>>>>> '+ str(i) + ' <<<<<页数据抓取完毕!!' ) # 打印抓取页面的进程
res.encoding = res.apparent_encoding
soup = BeautifulSoup(res.text,'html.parser')
# 获取楼盘名字,并追加保存在name_list列表中
name = soup.find_all('h3')
for a in name:
name_list.append(a.text)
# 获取楼盘面积大小,并追加保存在area_list列表中
area = soup.find_all(class_="type")
for a in area:
area_list.append(a.text)
# 获取楼盘地址,并追加保存在add_list列表中
add = soup.find_all(class_="add")
for a in add:
add_list.append(a.text)
# 获取楼盘价格,并追加保存在price_list列表中
price = soup.find_all('li',class_="price")
for b in price:
price_list.append(b.text)
i += 1
x = 0
y = 27 # 每一页有27个楼盘信息需要爬取,进行for循环不要超出。并通过append一行一行将楼盘信息保存到Excel表格中
while x < y*(i-1):
ws.append([str(x+1),name_list[x],area_list[x],price_list[x],add_list[x]])
x += 1
wb.save("e:sample.xlsx") # 将文件存盘