Python---爬虫案例

例1、爬取公众号文章中的图片。

1,首先打开要获取公众号文章的地址
2,按下F12,再按Ctrl Shift C,然后鼠标移动到图片位置,然后观察控制台中显示图片对应的代码位置
3,分析该位置的代码段
在这里插入图片描述
代码段如下:
<img data-s="300,640" data-type="png" data-src="http://mmbiz.qpic.cn/mmbiz_png/xXrickrc6JTO9TThicnuGGR7DtzWtslaBl2kjpHsq1xSmicGGreQ5yUTK6W8JlX30aB50615I06bqib4Bk17F4nV8A/0?wx_fmt=png" style="width: 677px !important; height: auto !important; visibility: visible !important;" class data-ratio="0.5602272727272727" data-w="880" _width="677px" src="http://mmbiz.qpic.cn/mmbiz_png/xXrickrc6JTO9TThicnuGGR7DtzWtslaBl2kjpH…50615I06bqib4Bk17F4nV8A/640?wx_fmt=png&tp=webp&wxfrom=5&wx_lazy=1&wx_co=1" crossorigin="anonymous" data-fail="0">
这里我们观察这个代码段的格式:然后编写正则表达式

pattern = ‘data-type=“png” data-src="(.+?)"’
?       ---  匹配位于?之前的0个或1个字符
+		---  匹配位于+之前的字符或子模块的1次或多次的出现
. 		---  匹配除换行符以外的任意单个字符
from re import findall
from urllib.request import urlopen

url = 'https://mp.weixin.qq.com/s?__biz=MzI4MzM2MDgyMQ==&mid=2247486249&idx=1&sn=a37d079f541b194970428fb2fd7a1ed4&chksm=eb8aa073dcfd2965f2d48c5ae9341a7f8a1c2ae2c79a68c7d2476d8573c91e1de2e237c98534&scene=21#wechat_redirect' #这个为要爬取公众号图片的地址
with urlopen(url) as fp:
    content=fp.read().decode('utf-8')

pattern = 'data-type="png" data-src="(.+?)"'
#查找所有图片链接地址
result = findall(pattern, content)  #捕获分组
#逐个读取图片数据,并写入本地文件
path='f:/test/'#把图片存放到f盘下的test文件夹中
for index, item in enumerate(result):
    with urlopen(str(item)) as fp:
        with open(path+str(index)+'.png','wb') as fp1: 
            fp1.write(fp.read())

例2、使用scrapy框架编写爬虫程序。

首先安装scrapy,打开cmd运行pip install scrapy
若出错:attrs() got an unexpected keyword argument ‘eq’
则运行:pip3 install attrs==19.2.0 -i http://mirrors.aliyun.com/pypi/simple --trusted-host mirrors.aliyun.com即可

运行cmd开始创建项目,根据指定位置可以切换路径
创建一个项目:scrapy startproject sqsq为项目名可随意
cd sq
在这里插入图片描述
在这里插入图片描述
出现这样表示scrapy框架已经搭建成功

例3、使用scrapy框架编写爬虫程序,爬取天涯小说。

这里以例2为基础继续
scrapy genspider xiaoshuosq bbs.tianya.cn/post-16-1126849-1.shtml
xiaoshuosq为爬虫名称
bbs.tianya.cn/post-16-1126849-1.shtml为爬虫起始位置,这里是天涯小说第一页
在这里插入图片描述
之后打开创建的xiaoshuosq爬虫
在这里插入图片描述
编写如下代码:

# -*- coding: utf-8 -*-
import scrapy


class XiaoshuosqSpider(scrapy.Spider):
    name = 'xiaoshuosq'#这里的是你创建的爬虫名称
    allowed_domains = ['http://bbs.tianya.cn/post-16-1126849-1.shtml']
    start_urls = ['http://bbs.tianya.cn/post-16-1126849-1.shtml/']

    def parse(self, response):
        content=[]
        for i in response.xpath('//div'):
            if i.xpath('@_hostid').extract()==['13357319']:
                for j in i.xpath('div//div'):
                    c = j.xpath('text()').extract()
                    g = lambda x:x.strip('\n\r\u3000').replace('<br>','\n').replace('|','')
                    c = '\n'.join(map(g.c)).strip()
                    content.append(c)
        with open('F:\result.txt','a+',enconding='utf8') as fp:
            fp.writelines(content)
        url=response.url
        d = url[url.rindex('-')+1:url.rindex('.')]
        u = 'http://bbs.tianya.cn/post-16-1126849-{0}.shtml'
        next_url = u.format(int(d)+1)
        try:
            yield scrapy.Request(url=next_url,callback=self.parse)
        except:
            pass

保存该爬虫
然后scrapy crwal xiaoshuosq这里的xiaoshuosq是你创建的爬虫名称

例4、使用requests库爬取微信公众号“Python小屋”文章“Python使用集合实现素数筛选法”中的所有超链接。

# -*- coding: utf-8 -*-
"""
Created on Mon Jun  1 21:40:19 2020

@author: 78708
"""

#使用requests库爬取微信公众号“Python小屋”文章“Python使用集合实现素数筛选法”中的所有超链接
import requests
import re
url = 'https://mp.weixin.qq.com/s?__biz=MzI4MzM2MDgyMQ==&mid=2247486531&idx=1&sn=7eeb27a03e2ee8ab4152563bb110f248&chksm=eb8aa719dcfd2e0f7b1731cfd8aa74114d68facf1809d7cdb0601e3d3be8fb287cfc035002c6#rd'
r = requests.get(url)
print(r.status_code )      #响应状态码
#print(r.text[:300]  )      #查看网页源代码前300个字符
print('筛选法' in r.text  )
print(r.encoding )
links = re.findall(r'<a .*?href="(.+?)"', r.text)
#使用正则表达式查找所有超链接地址
for link in links:
    if link.startswith('http'):
        print(link)
        
from bs4 import BeautifulSoup
soup = BeautifulSoup(r.content, 'lxml')
for link in soup.findAll('a'):  #使用BeautifulSoup查找超链接地址
    href = link.get('href')
    if href.startswith('http'):      #只输出绝对地址
        print(href)

例5、读取并下载指定的URL的图片文件。

# -*- coding: utf-8 -*-
"""
Created on Mon Jun  1 21:39:44 2020

@author: 78708
"""

#读取并下载指定的URL的图片文件。

import requests
picUrl = r'https://www.python.org/static/opengraph-icon-200x200.png'
r = requests.get(picUrl)
print(r.status_code)
with open('G:\TIM\图片\wsq.png', 'wb') as fp:#G:\TIM\图片\wsq.png 为保存路径以及图片名称
    fp.write(r.content)                #把图像数据写入本地文件

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值