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 urlopenurl = '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 scrapyclass 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.urld = 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)                #把图像数据写入本地文件

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/379101.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

WinCE驱动开发问题精华集锦(二)

转自&#xff1a;http://hgh123.blog.163.com/blog/static/5980422120086183115543/ 感谢 我怎么能在PB左边的定制平台加进我的驱动呢&#xff1f; 两种办法&#xff1a; 1、在platform.bib或者project.bib的MODULES部分添加一条语句&#xff0c;例如&#xff1a; MyDriver.dll…

报错Unable to resolve target android-5

报错信息&#xff1a;Error:Unable to resolve target android-X&#xff08;X是一个数字&#xff09; 错误分析&#xff1a;这种错误一般大部分是SDK 版本不符所造成的&#xff0c;一般会在Ecplise工作空间导入项目时候出现此错误&#xff0c;一般提示&#xff1a;Error:Unabl…

matlab盒子分形维数_分形维数--matlab

一维曲线分形维数的matlab程序function DFractalDim(y,cellmax)%求输入一维信号的计盒分形维数%y是一维信号%cellmax:方格子的最大边长,可以取2的偶数次幂次(1,2,4,8...),取大于数据长度的偶数%D是y的计盒维数(一般情况下D>1),Dlim(log(N(e))/log(k/e)),if cellmaxerror(cel…

Java布尔类toString()方法及示例

Syntax: 句法&#xff1a; public String toString();public static String toString(boolean value);布尔类toString()方法 (Boolean class toString() method) toString() method is available in java.lang package. toString()方法在java.lang包中可用。 toString() metho…

pcm数据编码成为aac格式文件(可以在酷狗播放)

pcm数据编码成为aac格式文件&#xff08;可以在酷狗播放&#xff09; 关于其中的aac adts格式可以参考&#xff1a;AAC ADTS格式分析 main.c #include <stdio.h> #include <stdlib.h> #include <stdlib.h>#include <libavcodec/avcodec.h> #include …

Python---实验九

1、使用标准库urllib爬取“http://news.pdsu.edu.cn/info/1005/31269.htm”平顶山学院新闻网上的图片&#xff0c;要求:保存到F盘pic目录中&#xff0c;文件名称命名规则为“本人姓名” “_图片编号”&#xff0c;如姓名为张三的第一张图片命名为“张三_1.jpg”。 from re imp…

Request.Url学习(转)

原文地址&#xff1a;http://www.cnblogs.com/jame-peng1028/articles/1274207.html?login1#commentform 网址&#xff1a;http://localhost:1897/News/Press/Content.aspx/123?id1#tocRequest.ApplicationPath/Request.PhysicalPathD:\Projects\Solution\web\News\Press\Con…

32接上拉5v_51单片机P0口上拉电阻的选择

作为I/O口输出的时候时&#xff0c;输出低电平为0 输出高电平为高组态(并非5V&#xff0c;相当于悬空状态&#xff0c;也就是说P0 口不能真正的输出高电平)。给所接的负载提供电流&#xff0c;因此必须接(一电阻连接到VCC)&#xff0c;由电源通过这个上拉电阻给负载提供电流。P…

[转载]FPGA/CPLD重要设计思想及工程应用(时序及同步设计)

来源&#xff1a;http://www.eetop.cn/blog/html/11/317611-13412.html 数字电路中,时钟是整个电路最重要、最特殊的信号。 第一, 系统内大部分器件的动作都是在时钟的跳变沿上进行, 这就要求时钟信号时延差要非常小, 否则就可能造成时序逻辑状态出错. 第二, 时钟信号通常是系统…

duration java_Java Duration类| ofMinutes()方法与示例

duration javaDuration Class of Minutes()方法 (Duration Class ofMinutes() method) ofMinutes() method is available in java.time package. ofMinutes()方法在java.time包中可用。 ofMinutes() method is used to represent the given minutes value in this Duration. of…

实验五 图形设计

每复制一个方法都要绑定Paint事件 一、创建Windows窗体应用程序&#xff0c;要求如下&#xff1a;&#xff08;源代码运行界面&#xff0c;缺少任一项为0分&#xff0c;源代码只需粘贴绘制图形代码所在的方法&#xff0c;不用粘贴太多&#xff09; 例如: &#xff08;1&…

yuv编码成h264格式写成文件

yuv编码成h264格式写成文件 &#xff08;使用ffmpeg 编码yuv420p编码成h264格式&#xff09; #include <stdio.h> #include <stdlib.h> #include <stdint.h>#include <libavcodec/avcodec.h> #include <libavutil/time.h> #include <libavut…

c++ stl队列初始化_声明,初始化和访问向量| C ++ STL

c stl队列初始化Here, we have to declare, initialize and access a vector in C STL. 在这里&#xff0c;我们必须声明&#xff0c;初始化和访问C STL中的向量。 向量声明 (Vector declaration) Syntax: 句法&#xff1a; vector<data_type> vector_name;Since, vec…

ADO.NET与SQL Server数据库的交互

7.3.1 使用SqlConnection对象连接数据库 例如&#xff1a;建立与SQL Server数据库的连接。 string connstring"Data Sourceservername;uidusername;pwdpassword;Initial Catalogdbname";SqlConnection connnew SqlConnection(connstring);conn.Open(); 例如&#xf…

nsis 修改exe执行权限

通过修改注册表的方式&#xff0c;修改exe的执行权限。&#xff0c;以下例子是使用管理员运行。 ;添加admin权限 SectionWriteRegStr HKCU "SOFTWARE\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Layers" "$INSTDIR\spp.exe" "RUNASADMIN&qu…

linux ftp日志_linux学习笔记(一)——Linux分区和目录结构

linux学习笔记&#xff08;一&#xff09;——Linux分区和目录结构安装Linux时&#xff0c;手动挂载分区的情况下&#xff0c;/ 和 swap 是必须要挂载的&#xff0c;其他/home、/boot 等可以根据需要自行挂载。一般来说&#xff0c;简单的话&#xff0c;建议挂载三个分区&#…

C#通过VS连接MySQL数据库实现增删改查基本操作

创建一个数据库wsq 里面有一张beyondyanyu表 表里面有id(int)、names(varchar)、count(int)、passwords(varchar) 数据可以自己添 1、导入MySQL引用&#xff0c;你需要从官网或者其他地方下载&#xff0c;私聊我也可以 using MySql.Data.MySqlClient; 2、创建MySqlConnection对…

使用ffmpeg的filter处理yuv数据包括split filter(分流)、crop filter(裁剪)、vflip filter(垂直向上的翻转)、overlay filter(合成)

使用ffmpeg的filter处理yuv数据包括split filter(分流)、crop filter(裁剪)、vflip filter(垂直向上的翻转)、overlay filter(合成) #include <stdio.h>#include <libavcodec/avcodec.h> #include <libavformat/avformat.h> #include <libavfilter/avfil…

vc++ 6.0 堆栈_在C ++中使用链接列表实现堆栈

vc 6.0 堆栈To implement a stack using a linked list, basically we need to implement the push() and pop() operations of a stack using linked list. 要使用链接列表实现堆栈 &#xff0c;基本上&#xff0c;我们需要使用链接列表实现堆栈的push()和pop()操作。 Exampl…

烟雨小书店

烟雨小书店演示视频 源码