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("【数据库清理完成】")