Python爬虫简单实战,58同城西安二手笔电
2017-06-13 13:44
344 查看
from bs4 import BeautifulSoup import requests import time detail_url=[] #存放商品详情页地址 def get_detail_url(): homepage='http://xa.58.com/bijiben/?PGTID=0d100000-001e-3bf0-8466-349bfd89e876&ClickID=1' wb_data=requests.get(homepage) soup=BeautifulSoup(wb_data.text,'lxml') detail_urls=soup.select('tr.zzinfo > td.img > a') #提取图片部分包含的详情页链接 for element in detail_urls: if element.get('rel')==['nofollow']: #排除掉来自转转的商品 detail_url.append(element.get('href')) def get_info(url_list): get_detail_url() for url in url_list: data=[] wb_data=requests.get(url) soup=BeautifulSoup(wb_data.text,'lxml') cates=soup.select('span.crb_i > a')[0].text titles=soup.select('div.per_ad_left > div:nth-of-type(1) > h1')[0].text release_times=soup.select('div.per_ad_left > div:nth-of-type(1) > div:nth-of-type(1) > ul:nth-of-type(1) > li.time')[0].text #views=soup.select('div.per_ad_left > div:nth-of-type(1) > div:nth-of-type(1) > ul:nth-of-type(1) > li.count')[0].text prices=soup.select('ul.suUl > li > div.su_con > span.price')[0].text conditions=soup.select('ul.suUl > li:nth-of-type(2) > div:nth-of-type(2) > span:nth-of-type(1)')[0].text adds1=soup.select('ul.suUl > li:nth-of-type(3) > div.su_con > span.c_25d > a:nth-of-type(1)') #部分商品没有标明地址,地址部分需特殊处理 if adds1: adds1 = soup.select('ul.suUl > li:nth-of-type(3) > div.su_con > span.c_25d > a:nth-of-type(1)')[0].text else: adds1=' ' adds2=soup.select('ul.suUl > li:nth-of-type(3) > div.su_con > span.c_25d > a:nth-of-type(2)') if adds2: adds2 = soup.select('ul.suUl > li:nth-of-type(3) > div.su_con > span.c_25d > a:nth-of-type(2)')[0].text else: adds2=' ' data={ 'cate':cates, 'title':titles, 'release_time':release_times, 'price':prices, 'condition':conditions.replace(' ','').replace('\n','').replace('\r','').replace('\t',''), #剔除文本中的空格与换行符 'add':adds1+' '+adds2, } print(data) time.sleep(1) get_info(detail_url)
爬取网站URL:http://xa.58.com/bijibendiannao/0/?PGTID=0d3001df-001e-36ba-0791-107123270464&ClickID=1
爬取商品详情页面的标题、价格、成色、发布日期、地点等信息,不包含来自“转转”的商品。
通过对比普通商品标题元素与转转商品标题元素,可以看到普通商品的<a>部分中有一个rel="nofollow"的标示,以此为筛选条件过滤掉转转商品。
实际写代码时发现分析网页结构与元素位置是个比较麻烦的问题,比如在定位商品标题时,整个页面源码中共有四个位置(div部分中)出现了标题字样
用浏览器复制CSS选择器得到需要筛选元素的唯一路径(不一定唯一,试试),其中的nth-child(1)改为nth-of-type(1)。
在得到商品详情页的跳转链接时采用提取图片部分包含的链接的方法。
在抓取地址信息时,发现部分商品没有登记详细区域,这一块用判断条件做了特殊处理。
相关文章推荐
- Python开发简单爬虫之实战演练
- python爬虫实战之最简单的网页爬虫教程
- Python爬虫实战之爬取链家广州房价_01简单的单页爬虫
- Python爬虫实战入门三:简单的HTML解析——爬取腾讯新闻
- Python爬虫小项目(1):抓取转转网西安二手商品的详细信息并导入mongo,绘制图表,慢更
- 最简单的python爬虫实战——爬取王者荣耀皮肤及头像
- Python爬虫实战(三):简单爬取网页图片
- python开发简单爬虫:实战篇
- Python 爬虫简单实战之CSDN
- Python爬虫实战--(四)爬取58同城的商品数据
- python爬虫小练习之五:requests库小练习(58同城2手手机简单)
- Python爬虫实战(十一):两种简单的方法爬取动态网页
- 实践项目十:爬取百度百科Python词条相关1000个页面数据(慕课简单爬虫实战)
- Python爬虫简单实战:抓取小猪短租西安市前五页民房数据
- 用Python写爬虫爬取58同城二手交易数据
- python3.5简单爬虫爬取百度百科(参考imooc实战)
- Python爬虫实战入门二:从一个简单的HTTP请求开始
- 一段简单的 Python 爬虫程序
- Python与简单网络爬虫的编写
- [python脚本]一个简单的web爬虫(1)