python爬虫

大观:

反爬方法:

1. 请求头(Headers)验证

  • 机制 :检查User-AgentRefererCookie等请求头
  • 绕过方法
makefile 复制代码
headers = {
    "User-Agent": "Mozilla/5.0...",
    "Referer": "https://www.example.com",
    "Accept-Language": "zh-CN,zh;q=0.9"
}

header:采用字典数据结构

request基础使用模板:

ini 复制代码
import requests

headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36 Edg/138.0.0.0"
}
url = "https://www.sogou.com/web"
kw=input("请输入关键字")
param={
    'query':kw
}
response = requests.get(url=url,headers=headers,params=param)

requests使用案例:

  • request+正则表达式爬取百度图片网的图片

python 复制代码
import requests
import re

url = "https://pic.netbian.com/"
headers = {
    "user-agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36"
}
import os
path = "彼岸图网图片获取"
if not os.path.isdir(path):
    os.mkdir(path)

response = requests.get(url=url,headers=headers)
response.encoding = response.apparent_encoding
# print(response.text) # 打印请求成功的网页源码,和在网页右键查看源代码的内容一样的

"""
. 表示除空格外任意字符(除\n外)
* 表示匹配字符零次或多次
? 表示匹配字符零次或一次
.*? 非贪婪匹配
"""
# src后面存放的是链接,alt后面是图片的名字
# 直接(.*?)也是可以可以直接获取到链接,但是会匹配到其他不是我们想要的图片
# 我们可以在前面图片信息看到链接都是/u····开头的,所以我们就设定限定条件(/u.*?)这样就能匹配到我们想要的
parr = re.compile('src="(/u.*?)".alt="(.*?)"')
image = re.findall(parr,response.text)
for content in image:
    print(content)
# 对列表进行遍历
for i in image:
    link = i[0] # 获取链接
    name = i[1] # 获取名字
    """
    在文件夹下创建一个空jpg文件,打开方式以 'wb' 二进制读写方式
    @param res:图片请求的结果
    """
    with open(path+"/{}.jpg".format(name),"wb") as img:
        res = requests.get("https://pic.netbian.com"+link)
        img.write(res.content) # 将图片请求的结果内容写到jpg文件中
        img.close() # 关闭操作
    print(name+".jpg 获取成功······")
  • 在搜狗引擎搜索关键字,讲搜索后的页面生成html文件

ini 复制代码
import requests

headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36 Edg/138.0.0.0"
}
url = "https://www.sogou.com/web"
kw=input("请输入搜索的关键字")
param={
    'query':kw
}
response = requests.get(url=url,headers=headers,params=param)
page_text=response.text
fileName=kw+".html"
with open(fileName,'w',encoding='utf-8') as fp:
    fp.write(page_text)
print(fileName,"保存成功")
  • requests爬取图片网站的图片

python 复制代码
import os
import requests
from urllib.parse import urljoin
from bs4 import BeautifulSoup

# 创建保存图片的目录
# os.makedirs('58pic_images', exist_ok=True)
os.makedirs("110",)
url = "https://www.58pic.com/tupian-tupian/so.html?n_order=dnum&n_page_type=2&n_more_free=?tid=922493&utm_source=baidu&sdclkid=AL2R15fNArDibLgpxOF&bd_vid=11560355579337041163"

headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36 Edg/138.0.0.0"
}

try:
    # 获取网页内容
    response = requests.get(url, headers=headers)
    response.raise_for_status()
    html = response.text

    # 解析HTML
    soup = BeautifulSoup(html, "html.parser")

    # 查找所有img标签
    img_tags = soup.find_all('img')

    print(f"找到 {len(img_tags)} 张图片")

    for i, img in enumerate(img_tags, start=1):
        # 获取图片URL(优先使用data-src,如果没有则用src)
        img_url = img.get('data-src') or img.get('src')

        if not img_url:
            continue

        # 处理相对URL
        img_url = urljoin(url, img_url)

        try:
            # 下载图片
            img_data = requests.get(img_url, headers=headers, stream=True)
            img_data.raise_for_status()

            # 生成文件名
            file_name = f"58pic_images/image_{i}.jpg"

            # 保存图片
            with open(file_name, 'wb') as f:
                for chunk in img_data.iter_content(1024):
                    f.write(chunk)

            print(f"已下载: {file_name}")

        except Exception as e:
            print(f"下载失败 {img_url}: {e}")

except Exception as e:
    print(f"发生错误: {e}")

print("下载完成!")

匹配方式汇总:

  1. css选择器
  2. 正则表达式(Regex)
  3. 使用如BeautifulSoup、PyQuery(基于Don树)
  4. XPath
相关推荐
独行soc6 小时前
2025年渗透测试面试题总结-18(题目+回答)
android·python·科技·面试·职场和发展·渗透测试
S01d13r7 小时前
gunicorn + flask 处理高并发请求
python·flask·gunicorn
杜子不疼.7 小时前
《Python列表和元组:从入门到花式操作指南》
开发语言·python
pan0c237 小时前
数据处理与统计分析 —— numpy入门
python·numpy
max5006007 小时前
基于桥梁三维模型的无人机检测路径规划系统设计与实现
前端·javascript·python·算法·无人机·easyui
秋氘渔8 小时前
综合案例:Python 函数知识整合 — 学生成绩管理系统
开发语言·python
AI 嗯啦9 小时前
SQL详细语法教程(三)mysql的函数知识
android·开发语言·数据库·python·sql·mysql
databook9 小时前
把数学对象画出来:Manim Mobject类库速查手册
python·数学·动效
图灵学术计算机论文辅导10 小时前
傅里叶变换+attention机制,深耕深度学习领域
人工智能·python·深度学习·计算机网络·考研·机器学习·计算机视觉
ruleslol10 小时前
python30-正则表达式
python·正则表达式