爬虫实战第四天
任务
爬取58同城北京地区手机号页面 http://bj.58.com/shoujihao/
成果
爬取3000余条手机号的交易信息,并保存到本地数据库
源码
import requests
import time
from pymongo import MongoClient
from bs4 import BeautifulSoup
from multiprocessing import Pool
from threading import Thread
# 创建tong_cheng数据库,并在该数据库下面建立两个collection保存链接和详情
client = MongoClient('localhost', 27017)
tong_cheng = client['tong_cheng']
shoujihao_links = tong_cheng['shoujihao_links']
shoujihao_info = tong_cheng['shoujihao_info']
# spider 1 提取标题和链接
def get_links(page):
wb_data = requests.get(page)
soup = BeautifulSoup(wb_data.text, 'lxml')
titles = soup.select('#infolist > div > ul > div > ul > li > a.t > strong')
links = soup.select('#infolist > div > ul > div > ul > li > a.t')
for title, link in zip(titles, links):
title = title.get_text()
link = link['href']
data = {'标题': title, '链接': link}
shoujihao_links.insert_one(data)
# print(data)
# spider 2 提取对应link的页面详情
def get_info(link):
wb_data = requests.get(link)
soup = BeautifulSoup(wb_data.text, 'lxml')
data = {
'链接': link,
# 找到标题并处理字符串中的换行符、制表符和空格
'标题': soup.select('#main > div.col.detailPrimary.mb15 > div.col_sub.mainTitle > h1')[0].get_text().replace('\n', '').replace('\t', '').replace(' ', ''),
'价格': soup.select('#main > div.col.detailPrimary.mb15 > div.col_sub.sumary > ul > li > div.su_con > span')[0].get_text().replace('\n', '').replace('\t', '').replace(' ', '')
}
shoujihao_info.insert_one(data)
# print(data)
# 查询数据库中sheet表单中的数据量
def count():
while True:
# .find().count()不要忘了.count()
print('Saved links:%s\nSaved items:%s\n---------------' % (shoujihao_links.find().count(), shoujihao_info.find().count()))
time.sleep(5)
# 运行计数函数和查询函数(多进程和多线程)
def main(pages):
# 开启线程t,运行计数程序
t = Thread(target=count)
t.daemon = True
t.start()
# 主线程,第一步保存pages中的页面信息,包括标题和链接;
pool = Pool()
pool.map(get_links, pages)
# 主线程,第二步从数据中找到链接列表并得到页面详情
pool.map(get_info, [link['链接'] for link in shoujihao_links.find()])
pages = ['http://bj.58.com/shoujihao/pn{}/'.format(str(i)) for i in range(1, 111)]
if __name__ == '__main__':
main(pages)
小结
- 多进程可显著提高爬虫效率,多了解多进程、多线程相关知识。