python实现的爬取电影下载链接功能示例

yipeiwu_com5年前Python爬虫

本文实例讲述了python实现的爬取电影下载链接功能。分享给大家供大家参考,具体如下:

#!/usr/bin/python
#coding=UTF-8
import sys
import urllib2
import os
import chardet
from bs4 import BeautifulSoup
reload(sys)
sys.setdefaultencoding("utf-8")
#从电影html页面中获取视频下载地址
def get_movie_download_url(html):
  soup=BeautifulSoup(html,'html.parser')
  fixed_html=soup.prettify()
  td=soup.find('td',attrs={'style':'WORD-WRAP: break-word'})
  url_a=td.find('a')
  url_a=url_a.string
  return url_a
#从电影html页面中获取电影标题
def get_movie_title(html):
  soup=BeautifulSoup(html,'html.parser')
  fixed_html=soup.prettify()
  title=soup.find('h1')
  title=title.string
  return title
#访问url,返回html页面
def get_html(url):
  req=urllib2.Request(url)
  req.add_header('User-Agent','Mozilla/5.0')
  response=urllib2.urlopen(url)
  html=response.read()
  return html
#从电影列表页,获取电影的url,拼接好,存到列表后返回
def get_movie_list(url):
  m_list = []
  html = get_html(url)
  soup=BeautifulSoup(html,'html.parser')
  fixed_html=soup.prettify()
  a_urls=soup.find_all('a',attrs={'class':'ulink'})
  host = "http://www.ygdy8.net"
  for a_url in a_urls:
    m_url=a_url.get('href')
    m_list.append(host+m_url)
  return m_list
#存入txt文件
def file_edit(wr_str):
  f1 = open(r'e:\down_load_url.txt','a')
  f1.write(wr_str)
  f1.close()
#传入电影url的列表集合,获取下载地址,并写入文件
def write_to_txt(a_urls):
  for a_url in a_urls:
    html=get_html(a_url)
    html=html.decode('GBK')
    write_title=get_movie_title(html)
    write_url=get_movie_download_url(html)
    file_edit(write_title+"\n")
    file_edit(write_url+"\n")
    file_edit("\n")
#传入页数,返回这几页的url列表
def get_pages_url(num):
  urls_list = []
  url="http://www.ygdy8.net/html/gndy/dyzz/list_23_"
  for n in range(1,num+1):
    new_url = url+str(n)+".html"
    urls_list.append(new_url)
  return urls_list
if __name__=='__main__':
  pages = 2 #打算爬取几页电影
  p_url = get_pages_url(pages)
  for i in p_url:
    write_to_txt(get_movie_list(i))#执行写入
  print "done"

更多关于Python相关内容可查看本站专题:《Python Socket编程技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总

希望本文所述对大家Python程序设计有所帮助。

相关文章

Python网络爬虫出现乱码问题的解决方法

关于爬虫乱码有很多各式各样的问题,这里不仅是中文乱码,编码转换、还包括一些如日文、韩文 、俄文、藏文之类的乱码处理,因为解决方式是一致的,故在此统一说明。 网络爬虫出现乱码的原因 源...

python爬虫爬取微博评论案例详解

python爬虫爬取微博评论案例详解

前几天,杨超越编程大赛火了,大家都在报名参加,而我也是其中的一员。 在我们的项目中,我负责的是数据爬取这块,我主要是把对于杨超越 的每一条评论的相关信息。 数据格式:{"nam...

零基础写python爬虫之HTTP异常处理

先来说一说HTTP的异常处理问题。当urlopen不能够处理一个response时,产生urlError。不过通常的Python APIs异常如ValueError,TypeError等也...

python2.7实现爬虫网页数据

python2.7实现爬虫网页数据

最近刚学习Python,做了个简单的爬虫,作为一个简单的demo希望帮助和我一样的初学者。 代码使用python2.7做的爬虫  抓取51job上面的职位名,公司名,薪资,发布...

python爬虫(入门教程、视频教程) 原创

python的版本经过了python2.x和python3.x等版本,无论哪种版本,关于python爬虫相关的知识是融会贯通的,【听图阁-专注于Python设计】关于爬虫这个方便整理过很...