python爬虫request和BeautifulSoup使用

news/2024/7/19 11:57:39 标签: python, 爬虫, beautifulsoup

request使用

1.安装request

python">pip install request

image-20231028221900255

2.引入库

python">import requests

3.编写代码

发送请求

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

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

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

python">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属性判断是否请求成功

python">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

python">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.text
    print(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

python">pip install bs4
python">pip install bs4

image-20231028223709504

2.引入库

from bs4 import BeautifulSoup

3.编写代码

获取元素

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

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

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

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

此时我们代码如下

python">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.text
    soup = 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标签中间的内容

python">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.text
    soup = BeautifulSoup(html, "html.parser")
    all_titls = soup.findAll("span", attrs={"class": "title"})
    for title in all_titls:
        title_string = title.string
        print(title_string)
else:
    print("请求失败!")

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

image-20231028224526419

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

python">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.text
    soup = BeautifulSoup(html, "html.parser")
    all_titls = soup.findAll("span", attrs={"class": "title"})
    for title in all_titls:
        title_string = title.string
        if "/" not in title_string:
            print(title_string)
else:
    print("请求失败!")

image-20231028224813650

整合

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

打印所有页

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

image-20231028224946341

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

python">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.text
        soup = BeautifulSoup(html,"html.parser")
        all_titls = soup.findAll("span",attrs={"class":"title"})
        for title in all_titls:
            title_string = title.string
            if "/" not in title_string:
                print(title_string)
    else:
        print("请求失败!")

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

image-20231028225342725

存入txt

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

python">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.text
        soup = BeautifulSoup(html,"html.parser")
        all_titls = soup.findAll("span",attrs={"class":"title"})
        for title in all_titls:
            title_string = title.string
            if "/" 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.niftyadmin.cn/n/5131086.html

相关文章

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

试题一 软件架构设计 【问题1】(9分) 软件质量属性是影响软件架构设计的重要因素。请用200字以内的文字列举六种不同的软件质量属性名称并解释其含义。 常见的软件质量属性有多种,例如性能(Performance)、可用性(Ava…

本来打算做功能测试的,但是发现playwright太好玩了,玩了一天,功能测试进度为空

本文是作者的自言自语://todo 未完待续 https://blog.csdn.net/lineuman 微软果然有大牛啊!有能人的公司总是令人敬佩。 playwright这种级别的工具简直就是核弹级别的。 当我开始使用playwright的时候,嘭的一下,我的世界炸了&…

【斗罗二】霍雨浩迷惑审查,戴华斌故意挑衅,惨败者屈服下跪

【侵权联系删除】【文/郑尔巴金】 深度爆料,自《绝世唐门》宣布问世以来,其在国漫圈引发的关注和热议便如火如荼。作为《斗罗大陆》的续作,这部作品无疑继承了前作的荣光,甚至被无数粉丝期待着能再创辉煌。在各大社交媒体和国漫论…

Python机器学习基础(一)---数据集加载的方法

几个数据集加载的方式 鸢尾花练习资源(这个资源有瑕疵,index列和Species 都是带”“的字符串 导致一些加载现实问题,从而验证 还是pandas最好用) "index","Sepal.Length","Sepal.Width","Petal.Length","…

异步请求池——池式组件

前言 本文详细介绍异步请求池的实现过程,并使用DNS服务来测试异步请求池的性能。            两个必须牢记心中的概念: 同步:检测IO 与 读写IO 在同一个流程里异步:检测IO 与 读写IO 不在同一个流程 同步请求 与 异步请求…

机架式服务器介绍

大家都知道服务器分为机架式服务器、刀片式服务器、塔式服务器三类,今天小编就分别讲一讲这三种服务器,第一篇先来讲一讲机架式服务器的介绍。 机架式服务器定义:机架式服务器是安装在标准机柜中的服务器,一般采用19英寸的标准尺寸…

【AD9361 数字接口CMOS LVDSSPI】B 并行数据之CMOS

##接上一篇; 本节介绍 AD9361 数字接口CMOS &LVDS&SPI最后一张表中四种工作模式的具体配置及时序波形图。 目录 1、单端口半双工模式 (CMOS) *代称 SHC*换句话说,最大值是12‘b0111_1111_1111,即0x7FF&#xf…

JPA联合主键使用

在实际工作中,我们会经常遇到联合主键的情况,所以我用简单例子列举JPA两种实现联合主键的方式。 1、如何通过IdClass 实现联合主键 第一步:新建一个UserInfoID类,里面是联合主键 Data Builder NoArgsConstructor AllArgsConstructor publi…