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
相关推荐
Python×CATIA工业智造6 分钟前
Python迭代协议完全指南:从基础到高并发系统实现
python·pycharm
THMAIL15 分钟前
机器学习从入门到精通 - Transformer颠覆者:BERT与预训练模型实战解析
python·随机森林·机器学习·分类·bootstrap·bert·transformer
0wioiw028 分钟前
Python基础(①⑧Queue)
windows·python
Source.Liu1 小时前
【Python自动化】 21 Pandas Excel 操作完整指南
python·excel·pandas
urhero1 小时前
Python 制作的一个小说在线阅读工具
python·免费·小说·应用软件·小说在线阅读·无广告
跟橙姐学代码1 小时前
列表、元组与字典:Python开发者的三大必备利器,再向高手靠近一步
前端·python·ipython
计算机毕设残哥1 小时前
HDFS存储农业大数据的秘密是什么?高级大豆数据分析与可视化系统架构设计思路
大数据·hadoop·python·hdfs·数据分析·spark·django
蛋仔聊测试1 小时前
pytest源码解析(二)剖析 pytest 的核心组件
python·面试
寒水馨2 小时前
Windows 11 手动下载安装配置 uv、配置国内源
windows·python·国内源·uv·windows11
花花无缺2 小时前
python自动化-pytest-标记
后端·python