python爬虫request和BeautifulSoup使用

request使用

1.安装request

pip install request

image-20231028221900255

2.引入库

import requests

3.编写代码

发送请求

我们通过以下代码可以打开豆瓣top250的网站

response = requests.get(f"https://movie.douban.com/top250"

但因为该网站加入了反爬机制,所以我们需要在我们的请求报文的头部加入User-Agent的信息

headers ={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36"
}response = requests.get(f"https://movie.douban.com/top250",headers=headers)

User-Agent可以通过访问网站时按f12查看获取

image-20231028222657590

我们可以通过response的ok属性判断是否请求成功

import requests
headers ={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36"
}response = requests.get(f"https://movie.douban.com/top250",headers=headers)
if response.ok:print("请求成功!")
else:print("请求失败!")

此时如果请求成功,控制台就会打印请求成功!

image-20231028222826786

获取网页的html

我们可以通过response的text的属性来获取网页的html

import requests
headers ={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36"
}response = requests.get(f"https://movie.douban.com/top250",headers=headers)
if response.ok:html = response.textprint(html)
else:print("请求失败!")

此时请求成功就会打印页面的html了

image-20231028223025357

BeautifulSoup使用

Beautiful Soup是python的一个库,最主要的功能是从网页抓取数据。官方解释如下:

Beautiful Soup提供一些简单的、python式的函数用来处理导航、搜索、修改分析树等功能。它是一个工具箱,通过解析文档为用户提供需要抓取的数据,因为简单,所以不需要多少代码就可以写出一个完整的应用程序。

Beautiful Soup自动将输入文档转换为Unicode编码,输出文档转换为utf-8编码。你不需要考虑编码方式,除非文档没有指定一个编码方式,这时,Beautiful Soup就不能自动识别编码方式了。然后,你仅仅需要说明一下原始编码方式就可以了。

Beautiful Soup已成为和lxml、html6lib一样出色的python解释器,为用户灵活地提供不同的解析策略或强劲的速度。

简单的说,我们可以拿他来解析html页面,来获取html的元素

1.安装BeautifulSoup

要使用BeautifulSoup4需要先安装lxml,再安装bs4

pip install bs4
pip install bs4

image-20231028223709504

2.引入库

from bs4 import BeautifulSoup

3.编写代码

获取元素

我们通过BeautifulSoup()就可以得到解析后的soup对象

    soup = BeautifulSoup(html, "html.parser")

使用findAll函数就可以找到我们想要的元素,例如:我们想找到span标签中,class为title的元素

   all_titls = soup.findAll("span", attrs={"class": "title"})

此时我们代码如下

from bs4 import BeautifulSoup
import requests
headers ={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36"
}response = requests.get(f"https://movie.douban.com/top250",headers=headers)
if response.ok:html = response.textsoup = BeautifulSoup(html, "html.parser")all_titls = soup.findAll("span", attrs={"class": "title"})print(all_titls)
else:print("请求失败!")

运行结果image-20231028224135059

元素处理

我们虽然找到了span标签中,class为title的元素,但我们不需要span标签中的内容,所以我们需要对他进行处理

首先我们发现,all_titls其实是一个数组,所以我们可以遍历他,这样就可以得到每一个span元素,通过string的属性就可以得到span标签中间的内容

from bs4 import BeautifulSoup
import requests
headers ={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36"
}response = requests.get(f"https://movie.douban.com/top250",headers=headers)
if response.ok:html = response.textsoup = BeautifulSoup(html, "html.parser")all_titls = soup.findAll("span", attrs={"class": "title"})for title in all_titls:title_string = title.stringprint(title_string)
else:print("请求失败!")

此时我们发现,我们虽然得到span标签中间的内容,但其中含有电影名字的英文名这是我们不需要的

image-20231028224526419

通过观察我们发现,每个英文名前都是带有/的,所以我们可以判断其是否含有"/"来进行过滤

from bs4 import BeautifulSoup
import requests
headers ={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36"
}response = requests.get(f"https://movie.douban.com/top250",headers=headers)
if response.ok:html = response.textsoup = BeautifulSoup(html, "html.parser")all_titls = soup.findAll("span", attrs={"class": "title"})for title in all_titls:title_string = title.stringif "/" not in title_string:print(title_string)
else:print("请求失败!")

image-20231028224813650

整合

虽然此时我们打印出了我们想要的数据,但这只是其中一页的,且只是打印,并没有存入数据库或者某个文件里

打印所有页

通过观察第二页的路径,我们发现在点击第二页时系统会传一个start的属性,这个属性除以25在加1就是我们需要的页数,反过来就是 (页数-1)*25 = start

image-20231028224946341

所以我们可以通过for循环,依次传入0,25,50…

from bs4 import BeautifulSoup
import requests
headers ={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36"
}for start_num in range(0,250,25):response = requests.get(f"https://movie.douban.com/top250?start={start_num}",headers=headers)if response.ok:html = response.textsoup = BeautifulSoup(html,"html.parser")all_titls = soup.findAll("span",attrs={"class":"title"})for title in all_titls:title_string = title.stringif "/" not in title_string:print(title_string)else:print("请求失败!")

这样我们就得到了所有的电影名

image-20231028225342725

存入txt

这里我们演示将数据存入记事本中,我们定义个数组,将所有电影的名字存入该数组,最后遍历数组写入txt文件即可

from bs4 import BeautifulSoup
import requests
headers ={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36"
}
titles = []
for start_num in range(0,250,25):response = requests.get(f"https://movie.douban.com/top250?start={start_num}",headers=headers)if response.ok:html = response.textsoup = BeautifulSoup(html,"html.parser")all_titls = soup.findAll("span",attrs={"class":"title"})for title in all_titls:title_string = title.stringif "/" not in title_string:titles.append(title_string)else:print("请求失败!")
with open(r'豆瓣top250.txt', 'w') as f:for i in titles:f.write(i + '\n')

image-20231028225627360

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

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

相关文章

在 Windows 用 Chrome System Settings 设置代理

在 Windows 用 Chrome System Settings 设置代理 贴心提示:在设置代理之前,请确保您已经安装了 浏览器。 🔧 设置代理的详细步骤如下: 打开 浏览器,输入 //settings/system 并回车。 在「系统和网络设置」页面中&am…

C++----模板进阶

文章目录 非类型模板参数STL知识补充 类模板的特化函数模板特化类模板特化偏特化 模板的分离编译模板总结 非类型模板参数 模板参数分为类型形参与非类型形参。 类型形参:出现在模板参数列表中,跟在class或者typename之类的参数类型名称。 非类型形参…

Seata入门系列【15】@GlobalLock注解使用场景及源码分析

1 前言 在Seata 中提供了一个全局锁注解GlobalLock,字面意思是全局锁,搜索相关文档,发现资料很少,所以分析下它的应用场景和基本原理,首先看下源码中对该注解的说明: // 声明事务仅在单个本地RM中执行 //…

Docker Harbor概述及构建

Docker Harbor概述及构建 一、Docker Harbor 概述1.1、harbor 简介1.2、Harbor的优势1.3、Harbor 的核心组件1.4、Docker私有仓库 架构 二、Harbor构建Docker私有仓库2.1 环境配置2.2、部署Harbor服务2.2.1、上传dock-compose,并设置权限2.2.2、安装harbor-offline-…

软考系列(系统架构师)- 2011年系统架构师软考案例分析考点

试题一 软件架构(质量属性效用树、架构风险、敏感点、权衡点) 【问题2】(13分) 在架构评估过程中,需要正确识别系统的架构风险、敏感点和权衡点,并进行合理的架构决策。请用300字以内的文字给出系统架构风险…

MySQL主从复制(基于binlog日志方式)

目录 一、什么是主从复制?二、主从复制原理、存在问题和解决方法2.1.主从复制原理2.2.主从复制存在的问题以及解决办法2.3.主从复制的同步模型2.4.拓展—Mysql并行复制 三、主从复制之基于binlog日志方式3.1.bin-log日志简介3.2.bin-log的使用3.2.1.开启binlog3.2.2…

windows 安装小乌龟

这是什么 这里简单描述一下在windows上如何安装GIT代码管理工具和使用小乌龟版本来调用GIT,并且配置一下git相关信息,可以使用小乌龟来操作代码。也有一些常规git使用方法。 需要的资源 Git-2.42.0-64-bit.exe(这个是git代码管理工具&…

[已解决]安装的明明是pytorch-gpu,但是condalist却显示cpu版本,而且torch.cuda.is_available 也是flase

问题; 安装了gpu版本的pytorch,但是显示的torch.cuda.is_available()却是flase。 conda list查看 版本显示只有cpuonly 在网上找了半天,也没有解决办法。 仔细看了一下,发现,有个单独的包叫cpuonly,不知道…

【Python爬虫三天从0到1】Day1:爬虫核心

目录 1.HTTP协议与WEB开发 (1)简介 (2)请求协议和响应协议 2. requests&反爬破解 (1)UA反爬 (2)referer反爬 (3)cookie反爬 3.请求参数 &#x…

SpringBoot内置工具类之断言Assert的使用与部分解析

先例举一个service的demo中用来验证参数对象的封装方法,使用了Assert工具类后是不是比普通的 if(xxx) { throw new RuntimeException(msg) } 看上去要简洁多了? 断言Assert工具类简介 断言是一个判断逻辑,用来检查不该发生的情况&#xff…

GoLong的学习之路(十三)语法之标准库 log(日志包)的使用

上回书说到,flag的问题。这回说到日志。无论是软件开发的调试阶段还是软件上线之后的运行阶段,日志一直都是非常重要的一个环节,我们也应该养成在程序中记录日志的好习惯。 文章目录 log配置logger配置日志前缀配置日志输出位置自定义logger …

JavaScript_Pig Game切换当前玩家

const current0El document.getElementById(current--0); const current1El document.getElementById(current--1); if (dice ! 1) {currentScore dice;current0El.textContent currentScore;} else {} });这是我们上个文章写的代码,这个代码明显是有问题的&…