python3.0 爬虫示例(目标58)

#coding:utf-8
‘’’’’
@author: jsjxy
‘’’
import urllib.request
from bs4 import BeautifulSoup
from openpyxl import workbook # 写入Excel表所用
from openpyxl import load_workbook # 读取Excel表所用
import os
os.chdir(r’C:\Users\ChouSB\Desktop’) # 更改工作目录为桌面

def getPhone(二级地址):
if “https” in 二级地址:
二级地址=二级地址
else:
二级地址=“https:”+二级地址
page = urllib.request.urlopen(二级地址)
contents = page.read()
soup = BeautifulSoup(contents,“html.parser”)#文档对象
# print(soup)
联系方式 = soup.find(‘p’, class_=‘phone-num’)
if 联系方式:#填写了联系方式才去取值
联系方式 = soup.find(‘p’, class_=‘phone-num’).get_text()
return 联系方式

def getInfo(url):
#global ws # 全局工作表对象
page = urllib.request.urlopen(url)
# page = urllib.request.Request(‘https://ty.58.com/ershoufang/0/pn1/’)
contents = page.read()
soup = BeautifulSoup(contents,“html.parser”)#文档对象
源 = soup.find_all(‘div’, class_=‘list-info’)
sum = 0
for tag in 源:
二级地址 = tag.find_all(“a”)[0].get(“href”)
sum = sum+1
for div in tag:
div2 = div.findNext(“div”)
print(“sum::”,sum,
“标题::”,tag.find(“a”).get_text(),
“小区::”,tag.find(“p”,class_=“baseinfo”).find_next(“p”,class_=“baseinfo”).find(“a”).get_text().strip(),
“格局::”,tag.find(“span”).get_text(),
“大小::”,tag.find(“span”).find_next(“span”).get_text(),
“朝向::”,tag.find(“span”).find_next(“span”).find_next(“span”).get_text(),
“楼层::”,tag.find(“span”).find_next(“span”).find_next(“span”).find_next(“span”).get_text(),
“姓名::”,tag.find(“span”,class_=“jjrname-outer anxuan-qiye-text”).get_text(),
“价格::”,div2.find(“p”).get_text(),div2.find(“p”).find_next(“p”).get_text(),
“联系方式::”,getPhone(二级地址)
)
#sum = []
标题 = [tag.find(“a”).get_text()]
小区 = [tag.find(“p”,class_=“baseinfo”).find_next(“p”,class_=“baseinfo”).find(“a”).get_text().strip()]
格局 = [tag.find(“span”).get_text()]
大小 = [tag.find(“span”).find_next(“span”).get_text()]
朝向 = [tag.find(“span”).find_next(“span”).find_next(“span”).get_text()]
楼层 = [tag.find(“span”).find_next(“span”).find_next(“span”).find_next(“span”).get_text()]
姓名 = [tag.find(“span”,class_=“jjrname-outer anxuan-qiye-text”).get_text()]
价格 = [div2.find(“p”).get_text(),div2.find(“p”).find_next(“p”).get_text()]
联系方式 = [getPhone(二级地址)]
ws.append([标题[0],小区[0],格局[0],大小[0],朝向[0],楼层[0],姓名[0],价格[0],联系方式[0]])
#自动翻页
def urlPage():
page = 0
pageSum = 2
while page <= pageSum:
page = page + 1
url='https://ty.58.com/ershoufang/0/pn’+str(page)
print(url)
getInfo(url)
#写入EXCEL
def printExcel():
# 创建Excel表并写入数据
global wb
wb = workbook.Workbook() # 创建Excel对象
global ws
ws = wb.active # 获取当前正在操作的表对象
ws.append([‘标题’,‘小区’,‘格局’,‘大小’,‘朝向’,‘楼层’,‘姓名’,‘价格’,‘联系方式’])
urlPage()
wb.save(‘test2.xlsx’) # 存入所有信息后,保存为filename.

printExcel()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值