#一、引入selenium标签:几步,driver,爬虫,nth,child,import,div,csv,快速 From: https://blog.51cto.com/u_13488918/6011961
from selenium import webdriver
from time import sleep
#from selenium.webdriver.chrome.options import Options
#import xlrd
import csv
import os
#固定csv保存在桌面
os.chdir(r'C:\Users\Administrator\Desktop')
#二、打开网页
# 使用webkit无界面浏览器
# 如果路径为 exe 启动程序的路径,那么该路径需要加一个 r
driver =webdriver.Firefox()
# 获取指定网页的数据 start_urls
driver.get('https://movie.douban.com/top250')
driver.implicitly_wait(20)
#三、翻页、获取内容、写入CSV
#遍历循环20次
for o in range (1,13):
#遍历循环15次
sleep(0.5)
for i in range (1,26):
#获取标题和时间
#拼接字符串
data1 = driver.find_element_by_css_selector('.grid_view > li:nth-child('+str(i)+') > div:nth-child(1) > div:nth-child(2) > div:nth-child(1) > a:nth-child(1) > span:nth-child(1)').text
data2 = driver.find_element_by_css_selector('.grid_view > li:nth-child('+str(i)+') > div:nth-child(1) > div:nth-child(2) > div:nth-child(2) > p:nth-child(3) > span:nth-child(1)').text
print(data1, data2)
#写入csv
with open('豆瓣.csv', 'a+', newline = '\n')as f:
w = csv.writer(f)
w.writerow([data1, data2])
sleep(0.5)
#并进行点击翻页
driver.find_element_by_css_selector('.next > a:nth-child(2)').click()
driver.quit()