我的结果
链接.png
详情.png
我的代码
from bs4 import BeautifulSoup
import requests, pymongo, re, time, urllib, socket, json, random
# 基本页面
url = 'http://bj.58.com/shoujihao/{}/pn{}/'
# headers
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36'}
# 使用session
req_session = requests.session()
# 建立数据库
client = pymongo.MongoClient('localhost', 27017)
walden = client['walden']
phone_test = walden['phone_test']
phone_info_test = walden['phone_info_test']
# 从列表页面获取手机号和链接,并存入数据库,对应第一个结果图
def get_phone_url(url, page, who=1):
# 整理地址,注意who和page的位置
search_page = url.format(who, page)
web_data = req_session.get(search_page, headers = headers)
soup = BeautifulSoup(web_data.text, 'lxml')
# 如果页码超出范围则pass
if soup.find('strong'):
# 考虑到selector结构一样,为了区分广告条目,这里采用了find_all搭配正则
tel_numbers = soup.find_all('li', logr=re.compile('.*-1$'))
tel_urls = soup.find_all('li', logr=re.compile('.*-1$'))
for tel_number, tel_url in \
zip(tel_numbers, tel_urls):
tel_number = tel_number.get_text().split()[0]
# 嵌套find_all
tel_url = tel_url.find_all('a', 't')[0].get('href')
# 写入数据库
data = {'Url': tel_url, 'Number': tel_number}
print(data)
phone_test.insert_one(data)
else:
pass
# 从详情页面获取信息
def get_phone_info(url):
try:
web_data = req_session.get(url, headers=headers, timeout=6)
soup = BeautifulSoup(web_data.text, 'lxml')
# 以防404
four_o_four = '404' in soup.find('script', type='text/javascript').get('src').split('/')
if four_o_four:
pass
else:
title = ' '.join(soup.select('.col_sub h1')[0].get_text().split())
price = soup.select('.price')[0].get_text().strip()
time = soup.select('li.time')[0].get_text().strip()
# 不是所有页面都有区域,这里用正则表达做了一个判断
if re.findall('区域', str(soup.select('.col_sub'))):
region = soup.select('.su_con a')[0].get_text().strip()
else:
region = None
name = soup.select('a.tx')[0].get_text()
contact = soup.select('span.f20')[0].get_text().strip()
# 写入数据库
phone_info_test.insert_one({
'title': title,
'price': price,
'time': time,
'region': region,
'name': name,
'contact': contact
})
# 防止报错
except UnicodeDecodeError as e:
print('-----UnicodeDecodeError url:', url)
except urllib.error.URLError as e:
print("-----urlError url:", url)
except socket.timeout as e:
print("-----socket timout:", url)
# 从里【开始】,获取10页链接写入数据库
for single_page in range(10):
print('页数:',single_page + 1, '\n', '-'*60)
time.sleep(10)
get_phone_url(url, single_page)
# 从数据库获取链接
for item in phone_test.find():
print(item['Url'])
info_page = item['Url']
get_phone_info(info_page)
time.sleep(1)
我的感想:
- 我估计我花了5个多小时,处理了挺多大大小小的坑,主要的坑点在于:广告的剔除,个别结构差异的地方(页面超出范围、404等)要做判断,以及老是报错‘Max retries exceeded with url’
- 对于坑点:
-
我觉得我用正则来剔除广告有点“霸王硬上弓”,别的同学通过筛选链接来处理挺简单明了,但需要一些细心和意识。
广告.png
正常.png
从地址来剔除广告.png
-
- 对于‘Max retries exceeded with url’呢。以我目前的经验:要么等会弄,要么调整sleep的时间,要么加proxy,要么改headers,属于一种瞎子摸象的状态。
- 对于结构上的差异或许需要经验来培养意识,像404的排除,页码范围的超出,老师讲出来顺理成章,但自己操作起来还是挺生疏的。