Python---爬虫

文章目录


前言

Python爬虫是一种通过自动化程序爬取互联网上的信息的技术。爬虫可以自动访问网页并提取所需的数据,比如网站的文本、图片、视频等。Python是一种简单易学的编程语言,广泛用于开发爬虫程序。


一.Http请求/响应模块

requests模块

requests模块可以用于发送GET、POST、PUT、DELETE等各种类型的HTTP请求,并且可以处理URL参数、请求头、响应内容等。

常用函数:

请求函数

  • 发送GET请求,并返回一个Response对象
python 复制代码
requests.get(url)
  • 发送POST请求,并返回一个Response对象
python 复制代码
requests.post(url)

响应函数

  • 获取响应的文本内容
python 复制代码
response.text
  • 以字节(bytes)形式获取响应体的内容
python 复制代码
response.content
  • 获取Http响应的状态码
python 复制代码
response.status_code
  • 获取Http响应的头部信息
python 复制代码
response.headers
  • 获取响应的JSON格式数据
python 复制代码
response.json()

二.文本筛选模块

re模块

re模块是Python中的正则表达式模块,它提供了对字符串进行模式匹配和替换的功能。

  • 返回字符串中所有与正则表达式匹配的非重叠模式的列表。
python 复制代码
re.findall(pattern, string)

XPath模块

Python中的XPath模块是一个用于解析和操作XML文档的库。它可以通过使用XPath表达式来查找和选择XML文档中的节点,以便提取所需的数据。

python 复制代码
html.xpath("XPath路径")

XPath 路径表达式

XPath 表达式的基本语法是从一个根元素开始,然后沿着树向下选择元素、属性或文本。表达式可以是绝对路径或相对路径。

  • 绝对路径 :从根元素开始的路径。例如,/root/child 表示选择根元素 root 下的 child 元素。
  • 相对路径 :从当前节点开始的路径。例如,child/grandchild 表示选择当前 child 元素下的 grandchild 元素。

XPath 语法元素

  • 节点名称:选择具有特定名称的节点。
  • /:作为路径分隔符,表示从根节点或当前节点开始选择。
  • //:选择文档中的节点,不考虑它们的位置。
  • *:匹配任何元素节点。
  • @:用于选择属性。
  • []:用于指定条件。
  • .:表示当前节点。
  • ..:表示当前节点的父节点

演示案例:

html 复制代码
<bookstore>  
  <book>  
    <title lang="en">Harry Potter</title>  
    <author>J K. Rowling</author>  
    <year>2005</year>  
    <price>29.99</price>  
  </book>  
  <book>  
    <title lang="en">Learning XML</title>  
    <author>Erik T. Ray</author>  
    <year>2003</year>  
    <price>39.95</price>  
  </book>  
</bookstore>

示例 1: 选择所有 book 元素

html 复制代码
/bookstore/book

示例 2: 选择所有 title 元素

html 复制代码
//title

示例 3: 选择第一个 book 元素的 title

html 复制代码
/bookstore/book[1]/title

示例 4: 选择所有 title 元素,且这些元素的 lang 属性值为 en

html 复制代码
//title[@lang='en']

三. 爬虫模板

**第一步:**安装必要的库如:requests库
第二步:在爬取站点页面右键检查,查找User-Agent内容,如下图

第三步: 使用requests库向目标网页发送请求,并获取网页的HTML内容

python 复制代码
import requests  
  
header = {"User-Agent":"..."} 填入请求报文中User-Agent内容
url = 'http://example.com'  
response = requests.get(url,headers=header)   
response.encoding = 'utf-8'   如果有需要,设置正确的编码  
html_content = response.text  获取响应文本内容

爬虫案例

下面通过爬取站点​​​​​​ https://pic.netbian.com/的图片做一个演示。

  • **第一步:**发送Http请求访问需要爬取的网站
python 复制代码
import re
import requests
import os
header = {"User-Agent":"Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Mobile Safari/537.36 Edg/128.0.0.0"}
response = requests.get("https://pic.netbian.com/",headers=header)
#防止乱码对response返回数据进行解码
response.encoding = response.apparent_encoding
print(response.text)
  • 第二步:利用正则表达式/XPath路径筛选出图片链接的相对路径

正则:

python 复制代码
#利用正则表达式匹配以字符串 /uploads/allimg/ 开头,后面跟着一个或多个非双引号(")字符的序列
#此处findall函数会找出所有以/uploads/allimg/开头的图片链接的相对路径
image = re.findall("/uploads/allimg/[^\"]+",response.text)

XPath路径

python 复制代码
html = etree.HTML(response.text)
image = html.xpath('//a[@target="_blank"]/span/img/@src')
  • 第三步: 创建图片链接的绝对路径

如下图,不难发现第二步获取的图片链接与图片源中的链接还有差别,此时需要我们将获取的相对链接扩展为绝对链接

python 复制代码
#image获取的是图片链接的相对路径,绝对路径需要添加https://pic.netbian.com/
#创建空列表link用于存储图片链接的绝对路径
link = []
#利用for循将图片链接的绝对路径添加到空列表link中
for i in image:
    link.append("https://pic.netbian.com/"+i)
  • **第四步:**创建用于保存爬取图片的文件并保存爬取图片
python 复制代码
#for循环每次遍历一个图片链接
for i in range(1,len(link)+1):
    #遍历的同时创建一个保存图片的文件
    with open(f"爬虫/image{i}.jpg.","wb") as img:
        #向图片链接发送Http请求
        res = requests.get(link[i - 1])
        #将返回的字节数据写入文件
        img.write(res.content)
        img.close()

整体代码演示:

python 复制代码
import re
import requests
import os
header = {"User-Agent":"Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Mobile Safari/537.36 Edg/128.0.0.0"}
response = requests.get("https://pic.netbian.com/",headers=header)
response.encoding = response.apparent_encoding


image = re.findall("/uploads/allimg/[^\"]+",response.text)
link = []
for i in image:
    link.append("https://pic.netbian.com/"+i)

for i in range(1,len(link)+1):
    with open(f"爬虫/image{i}.jpg.","wb") as img:
        res = requests.get(link[i - 1])
        img.write(res.content)
        img.close()

总结

相关推荐
ac-er88889 分钟前
在Flask中处理后台任务
后端·python·flask
ac-er888816 分钟前
Flask中的钩子函数
后端·python·flask
o独酌o20 分钟前
递归的‘浅’理解
java·开发语言
Book_熬夜!22 分钟前
Python基础(六)——PyEcharts数据可视化初级版
开发语言·python·信息可视化·echarts·数据可视化
我的运维人生31 分钟前
利用Python与Ansible实现高效网络配置管理
网络·python·ansible·运维开发·技术共享
毕设木哥39 分钟前
计算机专业毕业设计推荐-基于python的汽车汽修保养服务平台
大数据·python·计算机·django·汽车·毕业设计·课程设计
m0_631270401 小时前
高级c语言(五)
c语言·开发语言
2401_858286111 小时前
53.【C语言】 字符函数和字符串函数(strcmp函数)
c语言·开发语言
bugtraq20211 小时前
闲鱼网页版开放,爬虫的难度指数级降低。
爬虫
程序猿练习生1 小时前
C++速通LeetCode中等第5题-无重复字符的最长字串
开发语言·c++·leetcode