python爬虫request和BeautifulSoup使用

request使用

1.安装request

python 复制代码
pip install request

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查看获取

我们可以通过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("请求失败!")

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

获取网页的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了

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

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("请求失败!")

运行结果

元素处理

我们虽然找到了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标签中间的内容,但其中含有电影名字的英文名这是我们不需要的

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

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("请求失败!")

整合

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

打印所有页

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

所以我们可以通过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("请求失败!")

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

存入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')
相关推荐
TechWJ5 小时前
PyPTO编程范式深度解读:让NPU开发像写Python一样简单
开发语言·python·cann·pypto
枷锁—sha6 小时前
【SRC】SQL注入WAF 绕过应对策略(二)
网络·数据库·python·sql·安全·网络安全
abluckyboy6 小时前
Java 实现求 n 的 n^n 次方的最后一位数字
java·python·算法
喵手6 小时前
Python爬虫实战:构建各地统计局数据发布板块的自动化索引爬虫(附CSV导出 + SQLite持久化存储)!
爬虫·python·爬虫实战·零基础python爬虫教学·采集数据csv导出·采集各地统计局数据发布数据·统计局数据采集
天天爱吃肉82187 小时前
跟着创意天才周杰伦学新能源汽车研发测试!3年从工程师到领域专家的成长秘籍!
数据库·python·算法·分类·汽车
m0_715575347 小时前
使用PyTorch构建你的第一个神经网络
jvm·数据库·python
甄心爱学习7 小时前
【leetcode】判断平衡二叉树
python·算法·leetcode
深蓝电商API7 小时前
滑块验证码破解思路与常见绕过方法
爬虫·python
Ulyanov7 小时前
Pymunk物理引擎深度解析:从入门到实战的2D物理模拟全攻略
python·游戏开发·pygame·物理引擎·pymunk
sensen_kiss7 小时前
INT303 Coursework1 爬取影视网站数据(如何爬虫网站数据)
爬虫·python·学习