search
HomeBackend DevelopmentPython Tutorial使用Python编写简单网络爬虫抓取视频下载资源

我第一次接触爬虫这东西是在今年的5月份,当时写了一个博客搜索引擎,所用到的爬虫也挺智能的,起码比电影来了这个站用到的爬虫水平高多了!

回到用Python写爬虫的话题。

Python一直是我主要使用的脚本语言,没有之一。Python的语言简洁灵活,标准库功能强大,平常可以用作计算器,文本编码转换,图片处理,批量下载,批量处理文本等。总之我很喜欢,也越用越上手,这么好用的一个工具,一般人我不告诉他。。。

因为其强大的字符串处理能力,以及urllib2,cookielib,re,threading这些模块的存在,用Python来写爬虫就简直易于反掌了。简单到什么程度呢。我当时跟某同学说,我写电影来了用到的几个爬虫以及数据整理的一堆零零散散的脚本代码行数总共不超过1000行,写电影来了这个网站也只有150来行代码。因为爬虫的代码在另外一台64位的黑苹果上,所以就不列出来,只列一下VPS上网站的代码,tornadoweb框架写的 :)

[xiaoxia@307232 movie_site]$ wc -l *.py template/*<br>  156 msite.py<br>   92 template/base.html<br>   79 template/category.html<br>   94 template/id.html<br>   47 template/index.html<br>   77 template/search.html

下面直接show一下爬虫的编写流程。以下内容仅供交流学习使用,没有别的意思。

以某湾的最新视频下载资源为例,其网址是

http://某piratebay.se/browse/200

因为该网页里有大量广告,只贴一下正文部分内容:

对于一个python爬虫,下载这个页面的源代码,一行代码足以。这里用到urllib2库。

>>> import urllib2<br />>>> html = urllib2.urlopen('http://某piratebay.se/browse/200').read()<br />>>> print 'size is', len(html)<br />size is 52977<br />

当然,也可以用os模块里的system函数调用wget命令来下载网页内容,对于掌握了wget或者curl工具的同学是很方便的。

使用Firebug观察网页结构,可以知道正文部分html是一个table。每一个资源就是一个tr标签。

而对于每一个资源,需要提取的信息有:

1、视频分类
2、资源名称
3、资源链接
4、资源大小
5、上传时间

就这么多就够了,如果有需要,还可以增加。

首先提取一段tr标签里的代码来观察一下。

<tr>
<br>  <td class="vertTh">
<br>   <center>
<br>    <a href="/browse/200" title="此目录中更多">视频</a><br><br>    (<a href="/browse/205" title="此目录中更多">电视</a>)<br>   </center>
<br>  </td>
<br>  <td>
<br><div class="detName">   <a href="/torrent/7782194/The_Walking_Dead_Season_3_Episodes_1-3_HDTV-x264" class="detLink" title="细节 The Walking Dead Season 3 Episodes 1-3 HDTV-x264">The Walking Dead Season 3 Episodes 1-3 HDTV-x264</a><br>
</div>
<br><a href="magnet:?xt=urn:btih:4f63d58e51c1a4a997c6f099b2b529bdbba72741&dn=The+Walking+Dead+Season+3+Episodes+1-3+HDTV-x264&tr=udp%3A%2F%2Ftracker.openbittorrent.com%3A80&tr=udp%3A%2F%2Ftracker.publicbt.com%3A80&tr=udp%3A%2F%2Ftracker.istole.it%3A6969&tr=udp%3A%2F%2Ftracker.ccc.de%3A80" title="Download this torrent using magnet"><img src="/static/imghwm/default1.png" data-src="//static.某piratebay.se/img/icon-magnet.gif" class="lazy" alt="Magnet link"></a>   <a href="//torrents.%E6%9F%90piratebay.se/7782194/The_Walking_Dead_Season_3_Episodes_1-3_HDTV-x264.7782194.TPB.torrent" title="下载种子"><img class="dl lazy" src="/static/imghwm/default1.png" data-src="//static.某piratebay.se/img/dl.gif" alt="下载"></a><img  src="/static/imghwm/default1.png" data-src="//static.某piratebay.se/img/11x11p.png" class="lazy" alt="使用Python编写简单网络爬虫抓取视频下载资源" ><img  src="/static/imghwm/default1.png" data-src="//static.某piratebay.se/img/11x11p.png" class="lazy" alt="使用Python编写简单网络爬虫抓取视频下载资源" ><br>   <font class="detDesc">已上传 <b>3 分钟前</b>, 大小 2 GiB, 上传者 <a class="detDesc" href="/user/paridha/" title="浏览 paridha">paridha</a></font><br>  </td>
<br>  <td align="right">0</td>
<br>  <td align="right">0</td>
<br> </tr>

下面用正则表达式来提取html代码中的内容。对正则表达式不了解的同学,可以去 http://docs.python.org/2/library/re.html 了解一下。

为何要用正则表达式而不用其他一些解析HTML或者DOM树的工具是有原因的。我之前试过用BeautifulSoup3来提取内容,后来发觉速度实在是慢死了啊,一秒钟能够处理100个内容,已经是我电脑的极限了。。。而换了正则表达式,编译后处理内容,速度上直接把它秒杀了!

提取这么多内容,我的正则表达式要如何写呢?

根据我以往的经验,“.*?”或者“.+?”这个东西是很好使的。不过也要注意一些小问题,实际用到的时候就会知道 :)

对于上面的tr标签代码,我首先需要让我的表达式匹配到的符号是

表示内容的开始,当然也可以是别的,只要不要错过需要的内容即可。然后我要匹配的内容是下面这个,获取视频分类。

(电视)

接着我要匹配资源链接了,

...

再到其他资源信息,

font class="detDesc">已上传 3 分钟前, 大小 2 GiB, 上传者

最后匹配

大功告成!

当然,最后的匹配可以不需要在正则表达式里表示出来,只要开始位置定位正确了,后面获取信息的位置也就正确了。

对正则表达式比较了解的朋友,可能知道怎么写了。我Show一下我写的表达式处理过程,

就这么简单,结果出来了,自我感觉挺欢喜的。

当然,这样设计的爬虫是有针对性的,定向爬取某一个站点的内容。也没有任何一个爬虫不会对收集到的链接进行筛选。通常可以使用BFS(宽度优先搜索算法)来爬取一个网站的所有页面链接。

完整的Python爬虫代码,爬取某湾最新的10页视频资源:

# coding: utf8<br />import urllib2<br />import re<br />import pymongo<br />db = pymongo.Connection().test<br />url = 'http://某piratebay.se/browse/200/%d/3'<br />find_re = re.compile(r'<tr>.+?\(.+?">(.+?)</a>.+?class="detLink".+?">(.+?)</a>.+?<a href="(magnet:.+?)" .+?已上传 <b>(.+?)</b>, 大小 (.+?),', re.DOTALL)<br /># 定向爬去10页最新的视频资源<br />for i in range(0, 10):<br />    u = url % (i)<br />    # 下载数据<br />    html = urllib2.urlopen(u).read()<br />    # 找到资源信息<br />    for x in find_re.findall(html):<br />        values = dict(<br />            category = x[0],<br />            name = x[1],<br />            magnet = x[2],<br />            time = x[3],<br />            size = x[4]<br />        )<br />        # 保存到数据库<br />        db.priate.save(values)<br />print 'Done!'

以上代码仅供思路展示,实际运行使用到mongodb数据库,同时可能因为无法访问某湾网站而无法得到正常结果。

所以说,电影来了网站用到的爬虫不难写,难的是获得数据后如何整理获取有用信息。例如,如何匹配一个影片信息跟一个资源,如何在影片信息库和视频链接之间建立关联,这些都需要不断尝试各种方法,最后选出比较靠谱的。

曾有某同学发邮件想花钱也要得到我的爬虫的源代码。
要是我真的给了,我的爬虫就几百来行代码,一张A4纸,他不会说,坑爹啊!!!……

都说现在是信息爆炸的时代,所以比的还是谁的数据挖掘能力强 :D

好吧,那么问题来了学习挖掘机(数据)技术到底哪家强?:D:D:D

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. C  : Learning Curves and Ease of UsePython vs. C : Learning Curves and Ease of UseApr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

Python vs. C  : Memory Management and ControlPython vs. C : Memory Management and ControlApr 19, 2025 am 12:17 AM

Python and C have significant differences in memory management and control. 1. Python uses automatic memory management, based on reference counting and garbage collection, simplifying the work of programmers. 2.C requires manual management of memory, providing more control but increasing complexity and error risk. Which language to choose should be based on project requirements and team technology stack.

Python for Scientific Computing: A Detailed LookPython for Scientific Computing: A Detailed LookApr 19, 2025 am 12:15 AM

Python's applications in scientific computing include data analysis, machine learning, numerical simulation and visualization. 1.Numpy provides efficient multi-dimensional arrays and mathematical functions. 2. SciPy extends Numpy functionality and provides optimization and linear algebra tools. 3. Pandas is used for data processing and analysis. 4.Matplotlib is used to generate various graphs and visual results.

Python and C  : Finding the Right ToolPython and C : Finding the Right ToolApr 19, 2025 am 12:04 AM

Whether to choose Python or C depends on project requirements: 1) Python is suitable for rapid development, data science, and scripting because of its concise syntax and rich libraries; 2) C is suitable for scenarios that require high performance and underlying control, such as system programming and game development, because of its compilation and manual memory management.

Python for Data Science and Machine LearningPython for Data Science and Machine LearningApr 19, 2025 am 12:02 AM

Python is widely used in data science and machine learning, mainly relying on its simplicity and a powerful library ecosystem. 1) Pandas is used for data processing and analysis, 2) Numpy provides efficient numerical calculations, and 3) Scikit-learn is used for machine learning model construction and optimization, these libraries make Python an ideal tool for data science and machine learning.

Learning Python: Is 2 Hours of Daily Study Sufficient?Learning Python: Is 2 Hours of Daily Study Sufficient?Apr 18, 2025 am 12:22 AM

Is it enough to learn Python for two hours a day? It depends on your goals and learning methods. 1) Develop a clear learning plan, 2) Select appropriate learning resources and methods, 3) Practice and review and consolidate hands-on practice and review and consolidate, and you can gradually master the basic knowledge and advanced functions of Python during this period.

Python for Web Development: Key ApplicationsPython for Web Development: Key ApplicationsApr 18, 2025 am 12:20 AM

Key applications of Python in web development include the use of Django and Flask frameworks, API development, data analysis and visualization, machine learning and AI, and performance optimization. 1. Django and Flask framework: Django is suitable for rapid development of complex applications, and Flask is suitable for small or highly customized projects. 2. API development: Use Flask or DjangoRESTFramework to build RESTfulAPI. 3. Data analysis and visualization: Use Python to process data and display it through the web interface. 4. Machine Learning and AI: Python is used to build intelligent web applications. 5. Performance optimization: optimized through asynchronous programming, caching and code

Python vs. C  : Exploring Performance and EfficiencyPython vs. C : Exploring Performance and EfficiencyApr 18, 2025 am 12:20 AM

Python is better than C in development efficiency, but C is higher in execution performance. 1. Python's concise syntax and rich libraries improve development efficiency. 2.C's compilation-type characteristics and hardware control improve execution performance. When making a choice, you need to weigh the development speed and execution efficiency based on project needs.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.