Python作业1:Scrapy爬取学堂在线+链家二手房EEthunder

爬取学堂在线的计算机类课程页面内容。

要求将课程名称、老师、所属学校和选课人数信息,保存到一个csv文件中。

链接:

importscrapy

classStudyhallItem(scrapy.Item):

#definethefieldsforyouritemherelike:

#name=scrapy.Field()

name=scrapy.Field()#课程名

teacher=scrapy.Field()#老师

school=scrapy.Field()#学校

peopleNum=scrapy.Field()#选课人数

pass

ITEM_PIPELINES=

fromitemadapterimportItemAdapter

importcsv

classStudyhallPipeline(object):

defopen_spider(self,spider):

try:

"""打开csv文件"""

self.file=open('StudyHallData.csv','w',encoding='utf-8',newline='')

self.csv=csv.writer(self.file)

exceptExceptionase:

print(e)

defprocess_item(self,item,spider):

self.csv.writerow(list(item.values()))

returnitem

defclose_spider(self,spider):

self.file.close()

importjson

frompprintimportpprint

fromstudyHall.itemsimportStudyhallItem

classstudyHallSpider(scrapy.spiders.Spider):

name='studyHall'

allowed_domains=['www.xuetangx.com/']

"""data从浏览器中查看得来"""

data='{"query":"","chief_org":[],"classify":["1"],"selling_type":[],"status":[],"appid":10000}'

"""标头从浏览器中复制"""

headers={

'Host':'www.xuetangx.com',

'authority':'www.xuetangx.com',

'method':'POST',

'path':'/api/v1/lms/get_product_list/page=1',

'accept':'application/json,text/plain,*/*',

'accept-encoding':'gzip,deflate,br',

'accept-language':'zh',

'content-type':'application/json',

'cookie':'_ga=GA1.2.192047866.1605620269;provider=xuetang;django_language=zh',

'django-language':'zh',

'sec-fetch-dest':'empty',

'sec-fetch-mode':'cors',

'sec-fetch-site':'same-origin',

'user-agent':'Mozilla/5.0(WindowsNT10.0;Win64;x64)AppleWebKit/537.36(KHTML,likeGecko)Chrome/86.0.4240.198Safari/537.36Edg/86.0.622.69',

'x-client':'web',

'xtbz':'xt'

}

defstart_requests(self):

"""使用start_requests创建post请求"""

forpageinrange(1,6):

"""爬取5页信息"""

yieldscrapy.FormRequest(

url=self.url_pat.format(page),

headers=self.headers,

method='POST',

body=self.data,

callback=self.parse

)

defparse(self,response):

msg=json.loads(response.body)

foreachinmsg['data']['product_list']:

item=StudyhallItem()

item['name']=each['name']

item['school']=each['org']['name']

item['peopleNum']=each['count']

teacherList=[]

#因为有些课程有多个老师,需要逐一保存,写入一条记录

forteacherineach['teacher']:

teacherList.append(teacher['name'])

item['teacher']=','.join(teacherList)

yielditem

截取一部分爬取的数据如下:

要求爬取北京市东城、西城、海淀和朝阳四个城区的数据(每个区爬取5页),将楼盘名称、总价、平米数、单价保存到json文件中。

classHomelinkItem(scrapy.Item):

location=scrapy.Field()#城区

name=scrapy.Field()#名称

area=scrapy.Field()#面积

TTprice=scrapy.Field()#总价

UnitPrice=scrapy.Field()#单价

BOT_NAME='homeLink'

SPIDER_MODULES=['homeLink.spiders']

NEWSPIDER_MODULE='homeLink.spiders'

ITEM_PIPELINES={'homeLink.pipelines.HomelinkPipeline':300,}

#Crawlresponsiblybyidentifyingyourself(andyourwebsite)ontheuser-agent

#Obeyrobots.txtrules

ROBOTSTXT_OBEY=False

"""对付反爬虫"""

importrandom

#useragent列表

USER_AGENT_LIST=[

'MSIE(MSIE6.0;X11;Linux;i686)Opera7.23',

'Opera/9.20(Macintosh;IntelMacOSX;U;en)',

'Opera/9.0(Macintosh;PPCMacOSX;U;en)',

'iTunes/9.0.3(Macintosh;U;IntelMacOSX10_6_2;en-ca)',

'Mozilla/4.76[en_jp](X11;U;SunOS5.8sun4u)',

'iTunes/4.2(Macintosh;U;PPCMacOSX10.2)',

'Mozilla/5.0(Macintosh;IntelMacOSX10.6;rv:5.0)Gecko/20100101Firefox/5.0',

'Mozilla/5.0(Macintosh;IntelMacOSX10.6;rv:9.0)Gecko/20100101Firefox/9.0',

'Mozilla/5.0(Macintosh;IntelMacOSX10.8;rv:16.0)Gecko/20120813Firefox/16.0',

'Mozilla/4.77[en](X11;I;IRIX;646.5IP30)',

'Mozilla/4.8[en](X11;U;SunOS;5.7sun4u)'

]

#随机生成useragent

USER_AGENT=random.choice(USER_AGENT_LIST)

fromhomeLink.itemsimportHomelinkItem

classMySpider(scrapy.Spider):

name='homeLink'

allowed_domains=['bj.lianjia.com']

start_urls=[]

locations=['dongcheng','xicheng','haidian','chaoyang']#四个城区

forlocinlocations:

"""东城前五页"""

start_urls.append(url)

item=HomelinkItem()

foreachinresponse.xpath("//div[@id='content']/div[1]/ul/*"):

"""爬取该路径下的房区信息"""

"""楼盘地理位置"""

if(response.url.split('/')[-3]=='dongcheng'):

item['location']='东城'

elif(response.url.split('/')[-3]=='xicheng'):

item['location']='西城'

elif(response.url.split('/')[-3]=='haidian'):

item['location']='海淀'

elif(response.url.split('/')[-3]=='chaoyang'):

item['location']='朝阳'

"""获取楼盘名称"""

item['name']=each.xpath("./div[1]/div[@class='title']/a/text()").extract()

"""获取楼盘面积/平米"""

item['area']=each.xpath("./div[1]/div[@class='address']/div/text()").extract()[0].split('|')[1]

"""获取楼盘总价,以万为单位结尾"""

item['TTprice']=str(each.xpath("./div[1]/div[@class='priceInfo']/div[1]/span/text()").extract()[0])+'万'

"""获取楼盘单价"""

item['UnitPrice']=each.xpath("./div[1]/div[@class='priceInfo']/div[2]/span/text()").extract()

if(item['name']anditem['area']anditem['TTprice']anditem['UnitPrice']):

THE END
1.链家北京链家房地产经纪有限公司 | 地址:北京市海淀区西二旗西路2号院35号楼01层102-1 | 电话:10106188 | 京ICP备11024601号-18 | ? Copyright 2020 ke.com版权所有 | 违法和不良信息举报电话:010-86440676 | 违法和不良信息举报邮箱:jubaoyouxiang@ke.com http://homelink.com.cn/
2.易城二手房,930万,3室2厅,2卫,136.21平米安居客北京二手房网,提供东四环 板楼社区 一梯两户 南北三居 落地窗 采光好 方便看二手房出售信息,930万,3室2厅2卫,2010年,南北,精装修,普通住宅,地址位于华纺易城,北京房地产租售服务平台,安居客全房源网。https://beijing.anjuke.com/prop/view/A7015251419
3.北京链家在线二手房哪个好装修问答现在北京这边的二手房平均价格大概是61400块钱左右,我觉得这边的房价还是很贵的。在北京链家网上面有一https://ask.zx123.cn/show-4235631.html
4.链家在线二手房的微博链家在线二手房官方微博 +关注 g 私信 =主页 229关注 2621粉丝 39微博 北京链家房地产经纪有限公司 ü 简介: 链家在线二手房 T 友情链接 链家在线 北京链家在线 天津链家在线 大连链家在线 南京链家在线 成都链家在线 更多a 微关系 他的关注(228) 微博数据助手 粉丝群 元气桃子姜 微博房产报道 他https://weibo.com/youhuiquan
5.南京链家在线二手房土巴兔装修问答平台为网友提供各种南京链家在线二手房问题解答.土巴兔装修问答汇聚海量业主的装修经验和智慧,迅速为业主解决南京链家在线二手房的困惑https://www.to8to.com/ask/search/238760
6.北京房产网北京二手房网北京租房网北京我爱我家提供北京二手房信息、北京租房信息、北京二手房成交价格和北京二手房交易数据,是公认的北京房产网.找丰富房源,享放心服务就来北京我爱我家房产官网.https://bj.5i5j.com/
7.链家LianJia品牌介绍链家网链家地产二手房网链家租房链家成立于2001年,是以数据驱动的全价值链房产服务平台,提供二手房、新房、租房、旅居房产、海外房产等房产交易服务,并拥有业内独有的房屋数据、人群数据、交易数据,以数据技术驱动服务品质及行业效率的提升。经过多年的发展,链家目前已进驻北京、上海、广州、深圳、天津、成都、青岛、重庆、大连等28个城市和地区,全国https://www.maigoo.com/brand/26682.html
8.北京链家二手房中介费一般收多少北京的链家一般是2.7%二手房中介费即通过房屋中介公司进行二手房交易时支付给中介方的服务费,一般中介费为房屋成交价格的3%-5%。房屋出售方与房屋购买方都需要向中介方支付费用。中介服务费目前没有统一规定,一般按照行业内的习惯收取。 阿籽猫77 | 2024-11-23 16:27:12 链家收取服务费是房屋成交价的2%,如果是http://sjz.17house.com/tingyuan/aca319ae19cd0d5c0dc74f6a23eea1c9.html
9.爬取北京链家二手房数据链家api接口利用python爬取了北京链家主页的二手房数据,爬取时间为2020年1月8日。由于链家只显示了100页、每页30条,因此只能爬取3000条数据。 后续将爬取各区的小区名,对每个小区的在售二手房数据进行收集,这样能获得更多数据。 以下为程序代码,其最终生成houseinfo.csv文件,包含3000条在售二手房的各类数据。 https://blog.csdn.net/panlb1990/article/details/103895764