python—爬虫

简介:

1.1 介绍

通过过滤和分析HTML代码,实现对文件、图片等资源的获取,一般用到:

  • urllib和urllib2模块

  • 正则表达式(re模块)

  • requests模块

  • Scrapy框架


urllib库:

1)获取web页面

2)在远程http服务器上验证

3)表单提交(GET和POST)

4)异常处理(urllib2.URLError)

5)非http协议通信(ftp)


获取页面信息:

urllib2.urlopen(url,data,timeout)


构造Request:

reques = URLlib.Request(url,data,headers={})

response = urllib2.urlopen(request)

response.read()



1.2 实战1——爬取图片

爬取来源: http://tieba.baidu.com/p/4229162765(百度贴吧)


1)从网页链接源代码中查找数据,用于分析和提取url

   需下载的某张图片的url:

<img class="BDE_Image" src="http://imgsrc.baidu.com/forum/w%3D580/sign=d51025efb5fb43161a1f7a7210a54642/3887e950352ac65cf8452357fcf2b21193138a56.jpg" size="76453" width="400" height="600" style="cursor: url(&quot;http://tb2.bdstatic.com/tb/static-pb/img/cur_zin.cur&quot;), pointer;">


2)脚本

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#! /usr/bin/env python
import  urllib,urllib2
import  re
def  getHtml(url):
     page  =  urllib2.urlopen(url)
     return  page.read()
     
def  getImage(html):
     re_img  =  re. compile (r '<img class="BDE_Image" src="(.*?)".*?' )       #“(.*?)”问号表示非贪婪模式,匹配到最接近的双引号”,而不加问号则匹配到最后
     img_list  =  re_img.findall(html)
     =  1
     for  imgurl  in  img_list:
         print  imgurl
         urllib.urlretrieve(imgurl,filename = "%s.jpg"  % i)    #urllib.urlliburlretrieve下载,不指定文件名,则保持在当前目录
         =  i + 1
         
if  __name__  = =  "__main__" :
     url  =  "http://tieba.baidu.com/p/4229162765"
     html  =  getHtml(url)
     getImage(html)


运行结果:

1.png




1.3 实战2——爬取文本

爬取来源:https://www.qiushibaike.com/(糗事百科热门段子)

第一页:https://www.qiushibaike.com/

第二页:https://www.qiushibaike.com/8hr/page/2/

第三页:https://www.qiushibaike.com/8hr/page/3/


1)分析网页源码

   随机选择一个段子,审查元素,获取:作者、内容、点赞个数url位置,用于定义正则表达式

   

    作者位置:

1.png


    内容和点赞数位置:

3.png




2)代码

>>>>>> 脚本版本一 <<<<<<<<<<

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#!/usr/bin/env python
import  urllib,urllib2
import  re
page  =  1
url  =  "https://www.qiushibaike.com/8hr/page/"  + str (page)
headers  =  { "user-agent" : "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36" }   #访问正规的网站,一般需要user-agent
try :
     request  =  urllib2.Request(url,headers = headers)
     response  =  urllib2.urlopen(request)
     html  =  response.read()
     
except  urllib2.URLError,e:
     if  hasattr (e, "code" ):   #抛出异常时,e表示前面的错误类;判断该类中是否有code属性,有则打印出来
         print  e.code
     if  hasattr (e, "reason" ):
         print  e.reason
         
re_page  =  re. compile (r '<div class="author.*?<a.*?<img.*?alt="(.*?)">.*?<div.*?<span>(.*?)</span>.*?<i class="number">(\d+)</i>' ,re.S)   #正则表达式,re.S表示点号可以代表换行符
items  =  re_page.findall(html)
for  item  in  items:
     for  in  item:
         print  i


运行结果:

1.png



>>>>>>> 更新:脚本版本二 <<<<<<<<<<<

替换掉内容中网页换行符<br/>,然后去掉空格行,显示页数默认为第一页


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
32
33
34
35
36
37
38
39
40
41
42
#!/usr/bin/env python
#coding:utf-8
import  urllib,urllib2
import  re
 
def  getPage(page_num = 1 ):
     url  =  "https://www.qiushibaike.com/8hr/page/"  + str (page_num)
     headers  =  { "user-agent" : "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36" }
     try :
         request  =  urllib2.Request(url,headers = headers)
         response  =  urllib2.urlopen(request)
         html  =  response.read()
         return  html        
     except  urllib2.URLError,e:
         if  hasattr (e, "code" ):
             print  ( "连接服务器失败,错误代码 %s"  % e.code)
             return  None
             
         if  hasattr (e, "reason" ):
             print  ( "连接服务器失败,错误原因 %s"  % e.reason)
             return  None
             
def  getPageCoent(page_num = 1 ):
     html  =  getPage(page_num)
     re_page  =  re. compile (r '<div class="author.*?<a.*?<img.*?alt="(.*?)">.*?<div.*?<span>(.*?)</span>.*?<i class="number">(\d+)</i>' ,re.S)
     items  =  re_page.findall(html)
     page_contents  =  []                #定义空列表,用于存放内容
     replaceBR  =  re. compile (r '<br/>'
     for  item  in  items:
         content  =  item[ 1 ]
         content  =  replaceBR.sub( '\n' ,content)  #替换换行符
         page_contents.append([page_num,
                             item[ 0 ].strip(),   #删掉空格
                             content.strip(),
                             item[ 2 ].strip()])
     return  page_contents
     
if  __name__  = =  "__main__" :
    page_content  =  getPageCoent( 1 )
    for  item  in  page_content:
        for  in  item:
            print  str (i)  + "\n"


运行结果:

1.png



>>>>>> 继续更新:脚本版本三 <<<<<<<<<

实现交互式爬取

即每按一次enter键,显示一条段子,内容包括:页码、作者、段子内容、点赞数

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#!/usr/bin/env python
#coding:utf-8
import  urllib,urllib2
import  re
import  sys
 
def  getPage(page_num = 1 ):
     url  =  "https://www.qiushibaike.com/8hr/page/"  + str (page_num)
     headers  =  { "user-agent" : "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36" }
     
     try :
         request  =  urllib2.Request(url,headers = headers)
         response  =  urllib2.urlopen(request)
         html  =  response.read()
         return  html
                 
     except  urllib2.URLError,e:
         if  hasattr (e, "code" ):
             print  ( "连接服务器失败,错误代码 %s"  % e.code)
             return  None
             
         if  hasattr (e, "reason" ):
             print  ( "连接服务器失败,错误原因 %s"  % e.reason)
             return  None
             
def  getPageCoent(page_num = 1 ):
     html  =  getPage(page_num)
     re_page  =  re. compile (r '<div class="author.*?<a.*?<img.*?alt="(.*?)">.*?<div.*?<span>(.*?)</span>.*?<i class="number">(\d+)</i>' ,re.S)
     items  =  re_page.findall(html)
     page_contents  =  []
     replaceBR  =  re. compile (r '<br/>' )
     for  item  in  items:
         content  =  item[ 1 ]
         content  =  replaceBR.sub( '\n' ,content)
         page_contents.append([page_num,
                             item[ 0 ].strip(),
                             content.strip(),
                             item[ 2 ].strip()])
     return  page_contents
     
def  getOneStory(page_contents):
     for  story  in  page_contents:
         input  =  raw_input ()
         if  input  = =  "q"  or  input  = =  "Q" :
             sys.exit()
         print  "第%d页\t发布人:%s\t赞:%s\n%s\n"  % (story[ 0 ],story[ 1 ],story[ 3 ],story[ 2 ])
         
if  __name__  = =  "__main__" :
     print  "正在读取段子,按回车看新段子,按(Q|q)退出"
     num  =  1
     page_contents  =  getPageCoent(num)
     while  True :
         page_contents  =  getPageCoent(num)
         getOneStory(page_contents)
         num  + =  1


运行结果:

1.png










本文转自 huangzp168 51CTO博客,原文链接:http://blog.51cto.com/huangzp/2060411,如需转载请自行联系原作者
目录
相关文章
|
2月前
|
数据采集 存储 XML
Python爬虫:深入探索1688关键词接口获取之道
在数字化经济中,数据尤其在电商领域的价值日益凸显。1688作为中国领先的B2B平台,其关键词接口对商家至关重要。本文介绍如何通过Python爬虫技术,合法合规地获取1688关键词接口,助力商家洞察市场趋势,优化营销策略。
|
3月前
|
数据采集 Web App开发 监控
高效爬取B站评论:Python爬虫的最佳实践
高效爬取B站评论:Python爬虫的最佳实践
|
3月前
|
数据采集 缓存 定位技术
网络延迟对Python爬虫速度的影响分析
网络延迟对Python爬虫速度的影响分析
|
1天前
|
数据采集 存储 数据挖掘
深入剖析 Python 爬虫:淘宝商品详情数据抓取
深入剖析 Python 爬虫:淘宝商品详情数据抓取
|
4天前
|
存储 数据采集 数据库
Python爬虫实战:股票分时数据抓取与存储
Python爬虫实战:股票分时数据抓取与存储
|
30天前
|
数据采集 JSON 数据格式
Python爬虫:京东商品评论内容
京东商品评论接口为商家和消费者提供了重要工具。商家可分析评论优化产品,消费者则依赖评论做出购买决策。该接口通过HTTP请求获取评论内容、时间、点赞数等数据,支持分页和筛选好评、中评、差评。Python示例代码展示了如何调用接口并处理返回的JSON数据。应用场景包括产品优化、消费者决策辅助、市场竞争分析及舆情监测。
|
1月前
|
数据采集 供应链 API
Python爬虫与1688图片搜索API接口:深度解析与显著收益
在电子商务领域,数据是驱动业务决策的核心。阿里巴巴旗下的1688平台作为全球领先的B2B市场,提供了丰富的API接口,特别是图片搜索API(`item_search_img`),允许开发者通过上传图片搜索相似商品。本文介绍如何结合Python爬虫技术高效利用该接口,提升搜索效率和用户体验,助力企业实现自动化商品搜索、库存管理优化、竞品监控与定价策略调整等,显著提高运营效率和市场竞争力。
89 3
|
2月前
|
数据采集 存储 缓存
如何使用缓存技术提升Python爬虫效率
如何使用缓存技术提升Python爬虫效率
|
2月前
|
数据采集 JSON API
如何利用Python爬虫淘宝商品详情高级版(item_get_pro)API接口及返回值解析说明
本文介绍了如何利用Python爬虫技术调用淘宝商品详情高级版API接口(item_get_pro),获取商品的详细信息,包括标题、价格、销量等。文章涵盖了环境准备、API权限申请、请求构建和返回值解析等内容,强调了数据获取的合规性和安全性。
|
2月前
|
数据采集 Web App开发 监控
Python爬虫:爱奇艺榜单数据的实时监控
Python爬虫:爱奇艺榜单数据的实时监控

热门文章

最新文章

推荐镜像

更多