您的位置:首页 > 编程语言 > Python开发

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 爬虫 58同城