第一次爬虫之select 小猪短租
因为我是在成都 当然爬的是成都 短租房
需要爬取的是这些信息:
短住房的标题信息短住房的地址当然还有价格还有房东信息(头像,性别)hh
工具 个人喜欢用Pycharm, Select 方法 360 极速浏览器(chrome)同样
requests time BeautifulSoup
以上是所用的库。requests 当然是获取网站。BeautifulSoup 是用来解析我们获取的信息。time 是控制世界避免过快被网站拦截。库的安装这里就不说了 用Pycharm 很容易安装库。只需要在File 下 找到Project Interpreter 点击“+” 然后搜索需要的库。很容易对吧。当然Pycharm也有许多内置的库。
步入正题
1.进入页面
这是第一个 ,当我们往下 点击 下一页 链接是/search-duanzufang-p2-0/
第三页 不出意外肯定是这个/search-duanzufang-p3-0/ 聪明的你 肯定清楚了这规则了。我们直接构造多页 /search-duanzufang-p{}-0/’.format(number)for number in range(1,3)
5.找到需要爬取内容。我这里用的是360极速浏览器(chrome)利用f12 或用右键 审查元素 可以看到我们所需要的内容都在**#page_list**中 然后将鼠标移到所取内容中 再右键 Copy 找到 Copy selector 得到详细内容的Select #page_list > ul > li:nth-child(1) > a >#因为child(1) 是此页的第一个 我们获取是整个页面所有的 So 修改下 得到最终的#page_list > ul > li>a
3.获取我们所需内容
随意点进一个短住房。找到标题 继续右键Copy selectordiv.pho_info > h4(标题)span.pr5( 地址) #pricePart > div.day_l > span (价格) #floatRightBox > div.js_box.clearfix > div.member_pic > a > img (房东头像)
#floatRightBox > div.js_box.clearfix > div.w_240 > h6 > a (房东的名字) #floatRightBox > div.js_box.clearfix > div.member_pic > div (房东性别)
4.。后续步骤:
让浏览器 认为是真实用户访问 往往我们需要加上表头
这里就不讲解了,代码奉上 注释勉强看看
import requestsimport timefrom bs4 import BeautifulSoupheaders = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36'}def judgment_sex(class_name): #判断房东性别函数if class_name == ['member_ico1']:return '女'else:return '男'def get_links(url):#定义获取详细页的URl的函数wb_data =requests.get(url,headers=headers)soup =BeautifulSoup(wb_data.text,'lxml')links =soup.select('#page_list > ul > li> a') #url是详细页的信息for link in links:href =link.get("href")get_info(href) #循环出的URl 依此调用get_info()函数def get_info(url):wb_data =requests.get(url,headers=headers)soup =BeautifulSoup(wb_data.text,'lxml')tittles =soup.select('div.pho_info > h4') #标题addresses =soup.select('span.pr5') #地址prices =soup.select('#pricePart > div.day_l > span')#价格imgs =soup.select('#floatRightBox > div.js_box.clearfix > div.member_pic > a > img')#房东头像names = soup.select('#floatRightBox > div.js_box.clearfix > div.w_240 > h6 > a ')#房东的名字sexs =soup.select('#floatRightBox > div.js_box.clearfix > div.member_pic > div') #房东的性别for tittle,address,price,img,name,sex in zip(tittles,addresses,prices,imgs,names,sexs):data ={'tittle':tittle.get_text().strip(),'address':address.get_text().strip(),'price':price.get_text().strip(),'img':img.get("src"),'name':name.get_text(),'sex':judgment_sex(sex.get("class"))}print(data)if __name__== '__main__':urls =['/search-duanzufang-p{}-0/'.format(number)for number in range(1,3)]#构造多页URlfor single_url in urls:get_links(single_url)#循环调用——get_link函数time.sleep(2)
再附上结果,后面再发存放csv 文件,豆瓣电影 豆瓣音乐 豆瓣 图书。。。。
有错误欢迎指正,,,,,,