简单几步快速完成爬虫任务

Crq
Crq
管理员
1584
文章
0
粉丝
Linux教程评论8字数 248阅读0分49秒阅读模式
一、引入selenium
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()

weinxin
我的微信
微信号已复制
我的微信
这是我的微信扫一扫
 
Crq
  • 本文由 Crq 发表于2025年2月6日 03:18:41
  • 转载请注明:https://www.cncrq.com/12930.html
提高Python运行效率的5个技巧 Linux教程

提高Python运行效率的5个技巧

与其他编程语言相比,Python最大的特点就是能够让你在短时间内用极少的代码,实现大量的操作,比如:Java编写一个程序需要百行代码,而Python只需要十几行就能搞定。本篇文章为...
匿名

发表评论

匿名网友
:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:
确定

拖动滑块以完成验证