Python实战计划学习笔记(11)第二周作业

任务

抓取赶集网本站所有商品信息

思路

  1. 抓取所有频道URL,一共20个
  2. 每个频道读取至少70页商品URL信息,排除其中超出page导航范围的页面,存入数据库
  3. 从数据库中逐条读取商品URL,打开网页抓取商品信息,存入数据库

我的代码

一共编写了3个程序文件

  1. get_channels.py 用于读取20个频道的URL
  2. page_parser.py 用于处理商品URL和商品信息
  3. counts_ganji.py 用于监测数据库商品URL数
  • get_channels.py
from bs4 import BeautifulSoup
import requests

start_url = 'http://bj.ganji.com/wu/'
url_host = 'http://bj.ganji.com'

def get_channel_urls(url):
    web_data = requests.get(url)
    web_data.encoding = 'utf-8'  #读取网页出现乱码,要声明编码方式
    soup = BeautifulSoup(web_data.text, 'lxml')
    links = soup.select('dl.fenlei > dt > a')
    for link in links:
        page_url = url_host + link.get('href')
        channel_name = link.get_text()
        print(page_url)
    print('共计',len(links),'个频道。')

get_channel_urls(start_url)

#本程序用于获取以下频道列表

channel_list = '''
    http://bj.ganji.com/jiaju/
    http://bj.ganji.com/rirongbaihuo/
    http://bj.ganji.com/shouji/
    http://bj.ganji.com/shoujihaoma/
    http://bj.ganji.com/bangong/
    http://bj.ganji.com/nongyongpin/
    http://bj.ganji.com/jiadian/
    http://bj.ganji.com/ershoubijibendiannao/
    http://bj.ganji.com/ruanjiantushu/
    http://bj.ganji.com/yingyouyunfu/
    http://bj.ganji.com/diannao/
    http://bj.ganji.com/xianzhilipin/
    http://bj.ganji.com/fushixiaobaxuemao/
    http://bj.ganji.com/meironghuazhuang/
    http://bj.ganji.com/shuma/
    http://bj.ganji.com/laonianyongpin/
    http://bj.ganji.com/xuniwupin/
    http://bj.ganji.com/qitawupin/
    http://bj.ganji.com/ershoufree/
    http://bj.ganji.com/wupinjiaohuan/
'''
  • page_parser.py
from multiprocessing import Pool
from bs4 import BeautifulSoup
import requests
import time
import pymongo

client = pymongo.MongoClient('localhost',27017)
test_ganji = client['test_ganji']
url_list = test_ganji['url_list_ganji']
item_info = test_ganji['item_info']

channel_list = '''
    http://bj.ganji.com/jiaju/
    http://bj.ganji.com/rirongbaihuo/
    http://bj.ganji.com/shouji/
    http://bj.ganji.com/shoujihaoma/
    http://bj.ganji.com/bangong/
    http://bj.ganji.com/nongyongpin/
    http://bj.ganji.com/jiadian/
    http://bj.ganji.com/ershoubijibendiannao/
    http://bj.ganji.com/ruanjiantushu/
    http://bj.ganji.com/yingyouyunfu/
    http://bj.ganji.com/diannao/
    http://bj.ganji.com/xianzhilipin/
    http://bj.ganji.com/fushixiaobaxuemao/
    http://bj.ganji.com/meironghuazhuang/
    http://bj.ganji.com/shuma/
    http://bj.ganji.com/laonianyongpin/
    http://bj.ganji.com/xuniwupin/
    http://bj.ganji.com/qitawupin/
    http://bj.ganji.com/ershoufree/
    http://bj.ganji.com/wupinjiaohuan/
'''

#spider 1  爬取类别以下的所有在售条目
def get_links_from(channel,pages,who_sells = '3'):
    list_view = '{}a{}o{}/'.format(channel,str(who_sells),str(pages))
    print('reading ',list_view)
    web_data = requests.get(list_view)
    web_data.encoding = 'utf-8'  # 读取网页出现乱码,要声明编码方式
    time.sleep(4)
    soup = BeautifulSoup(web_data.text,'lxml')
    page_validity = soup.select('div.pageBox')
    if page_validity:
        print('Page ',pages,' is valid')
        if soup.find('div','ft-db'):
            for link in soup.select('a.ft-tit'):
                item_link = link.get('href')
                if item_link[7:19] != 'bj.ganji.com':
                    print('external link omitted')
                    pass
                elif url_list.find_one({'url':item_link}):
                    print('url exists')
                    pass
                else:
                    url_list.insert_one({'url':item_link})
                    print('saving',item_link)
        else:
            pass
    else:
        print('Page ', pages, ' is invalid')



#spider 2 爬取商品具体信息
def get_item_info(url):
    url = url.split('?')[0]
    time.sleep(2)
    if item_info.find_one({'url':url}):
        print('item exists')
    else:
        web_data = requests.get(url)
        soup = BeautifulSoup(web_data.text,'lxml')
        title = soup.title.text
        post_time = soup.select('ul.title-info-l.clearfix > li:nth-of-type(1) > i')[0].get_text().strip().split(' ')[0]
        type = soup.select('div.leftBox > div:nth-of-type(3) > div > ul > li:nth-of-type(1) > span > a')[0].get_text()
        price = soup.select('i.f22')[0].get_text()
        location = list(soup.select('div.leftBox > div:nth-of-type(3) > div > ul > li:nth-of-type(3)>a')[0].stripped_strings)[1:]
        contact_name = soup.select('div.leftBox > div:nth-of-type(3) > div > ul > li:nth-of-type(5)>li')
        if soup.select('div > ul > li:nth-of-type(6) > span.phoneNum-style'):
            contact_number = soup.select('div > ul > li:nth-of-type(6) > span.phoneNum-style')[0].get_text().strip()
        else:
            contact_number=''
        if soup.select('div > ul > li:nth-of-type(7) > span'):
            contact_qq = soup.select('div > ul > li:nth-of-type(7) > span')[0].get_text().strip()
        else:
            contact_qq = ''
        print('saving ',url)
        item_info.insert_one({'url':url,'title':title,'post_time':post_time,'type':type,'price':price,'location':location,'contact_name':contact_name[0].text.split('\xa0')[2][0:8].strip(),'contact_number':contact_number,'contact_qq':contact_qq})



#每个频道爬取70页
def get_all_links_from(channel):
    for num in range(1,71,1):
        get_links_from(channel,num)


#爬取所有频道的商品链接页URL
if __name__ == '__main__':
    pool = Pool(processes=1)
    pool.map(get_all_links_from, channel_list.split())




#读取的所有商品URL的具体信息
if __name__ == '__main__':
    items = []
    for link in list(url_list.find()):
        items.append(link['url'])
    pool = Pool()
    pool.map(get_item_info,items)
  • counts_ganji.py
import time
import pymongo

client = pymongo.MongoClient('localhost',27017)
test_ganji = client['test_ganji']
url_list = test_ganji['url_list_ganji']

while True:
    print(url_list.find().count())
    time.sleep(5)

运行结果

  1. 一共爬取了54943条商品记录
  2. 用多进程开4个爬虫性能明显提升
1.jpg

提高爬取效率的方法

  • 使用Proxy代理,减少sleep()
  • 单核CPU使用多线程,多核CPU使用多进程
  • 使用页面解析效率更高的lxml库
  • 使用异步非阻塞方式请求

程序中断后,去除重复的另一个方法

db_urls = [item['url'] for item in url_list.find()]
index_urls = [item['url'] for item in item_info.find()]
x = set(db_urls)
y = set(index_urls)
rest_of_urls = x - y
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,524评论 5 460
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,869评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,813评论 0 320
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,210评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,085评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,117评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,533评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,219评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,487评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,582评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,362评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,218评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,589评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,899评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,176评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,503评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,707评论 2 335

推荐阅读更多精彩内容