Selenium和pymongo的简单复习

import pymongo
client = pymongo.MongoClient(host='localhost',port=27017)
db = client.test
collection = db.books

import selenium
from selenium import webdriver
import time
options = webdriver.FirefoxOptions()
options.headless = True
browser = webdriver.Firefox(options=options)
page = 5
keyword = '爬虫'

while True:
    url = 'https://book.douban.com/subject_search?search_text='+ keyword + '&cat=1001&start=' + str(page*15)
    browser.get(url)
    print(url)
    detail_elements = browser.find_elements_by_class_name('detail')
    if detail_elements != []:
        page += 1
    else:
        print("【没有更多的数据了,抓取结束】")
        print("已抓取数据:", collection.count_documents({}), "条")
        break
    for detail_element in detail_elements:
        title = detail_element.find_element_by_class_name('title-text').text
        rate = detail_element.find_elements_by_class_name('rating_nums')
        if rate == []:
            rate = '暂无评分'
        else:
            rate = rate[0].text
        profile = detail_element.find_element_by_xpath("//div[@class='meta abstract']").text
#         print(title, rate, profile)
        result = collection.insert_one({'title':title, 'rate':rate, 'profile':profile})
#         print(result.inserted_id)

browser.quit()

for doc in collection.find({}):
    print(doc)
collection.delete_many({})  # 避免数据积累
if collection.count_documents({}) == 0:
    print("【数据库清理完成】")

转载于:https://www.cnblogs.com/lokvahkoor/p/10784624.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值