2019-01-14Selenium

Python自动化(一)使用Selenium+PhantomJS爬取电影下载链接

置顶 2017年09月12日 17:32:40 Gavinsun 阅读数:1109

 版权声明:本文为博主原创文章,未经博主允许不得转载。https://blog.csdn.net/gavinsun/article/details/77947751

采集第一页中所有电影的名称和迅雷链接

#coding:utf-8fromselenium import webdriverimport codecsdriver = webdriver.PhantomJS()driver.get("http://www.poxiao.com/mtype5.html")movies = driver.find_elements_by_xpath('//*/li/h3/a')cur_window = driver.current_window_handle#记录当前浏览器标签#遍历每部电影,并把电影的名字和对应的迅雷链接写入文件中。f = codecs.open("movies.csv",'w',encoding='utf-8')formovieinmovies:try:        f.write(movie.text)#输出电影的名字f.write(',')        movie.click()#点击电影,进入电影详情页面#在详情页中找到迅雷链接total_tab = driver.window_handles#获得当前浏览器打开的所有标签driver.switch_to.window(window_name=total_tab[1])#转到详情页thunder_link = driver.find_element_by_xpath('.//*/td[@class="sebc3"]/a')        f.write(thunder_link.get_attribute('href'))        driver.close()        driver.switch_to.window(window_name=cur_window)        f.write("\n")    except Exception,e:        continuef.close()driver.quit()

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

采集科幻片分类下的所有电影的名称和对应的迅雷链接。

# coding:utf-8fromseleniumimportwebdriverimportcodecsdriver = webdriver.PhantomJS()driver.get("http://www.poxiao.com/mtype5.html")cur_window = driver.current_window_handle# 记录当前浏览器标签f = codecs.open("movies.csv",'w', encoding='utf-8')whileTrue:printu"开始下载", driver.current_urlprintu"当前共打开{total_tab}个标签页。".format(total_tab=len(driver.window_handles))    movies = driver.find_elements_by_xpath('//*/li/h3/a')# 遍历每部电影,并把电影的名字和对应的迅雷链接写入文件中。formovieinmovies:        f.write(movie.text)# 输出电影的名字printmovie.text        f.write(',')        movie.click()# 点击电影,进入电影详情页面# 在详情页中找到迅雷链接total_tab = driver.window_handles# 获得当前浏览器打开的所有标签driver.switch_to.window(window_name=total_tab[1])# 转到详情页try:            thunder_link = driver.find_element_by_xpath('.//*/td[@class="sebc3"]/a')            f.write(thunder_link.get_attribute('href'))            f.write("\n")exceptException, e:printu"获得电影链接失败。"printdriver.current_urlfinally:            driver.close()            driver.switch_to.window(window_name=cur_window)# 找下一页,如果找不到,breaktry:        next_page = driver.find_element_by_link_text("下一页")exceptException, e:printu"没有找到下一页"printdriver.current_urlbreaknext_page.click()f.close()driver.quit()

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • pyspark.sql模块 模块上下文 Spark SQL和DataFrames的重要类: pyspark.sql...
    mpro阅读 9,537评论 0 13
  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,481评论 0 10
  • 好想有空去看看海。 看看海。天之蓝、水之蓝,水天一色,令人心驰神往。 看看海。背驮着山沟的贫瘠,穿着...
    亘雷阅读 366评论 0 17
  • 今天的天气格外的晴朗,温和的阳光映在脸上,像母亲的手轻柔地抚摸你的面颊……今天小淼学校补课,我难得有时间和...
    小淼宝贝阅读 120评论 0 0
  • 距离你说“我们在一起好不好”一个月。 在斜土路的酒店里,你抱着我哭, 第一次看你哭的那么伤心难过。心痛到骨子里。 ...
    Ermao阅读 251评论 2 1