如何反反爬虫

我们来讲最常见的反反爬虫方法

python 复制代码
import requests
r =requests.get('网页网址')
print(r.requests.headers)

一.使用简单的方法把请求头改为真的浏览器模式

python 复制代码
import requests
link='网页地址'
heraders={'User-Agent':''}
r=requests.get(link,headers=headers)
print(r.requsts.headers)

我们可以使用python的fake-uesragent,可以容易的切换User-Agent

pip install fake-uesragent

python 复制代码
from fake_useragent import UserAgent 
import requests

link=''
ua=UserAgent()
hearders={'User-Agent':''}
response=requests.grt(url=url,headers=headers)

print(response.status_code)
print(r.request.headers)

这里可以使用ua.random实现随机变换headers。每次生成的伪装表名不一样。我们还需要在headers里面写上Host和Referer

二.我们爬取的时候应该设置一段的时间限制:

python 复制代码
import time 
t1=time.time()
time.sleep(2)
t2=time.time()
total_time=t2-t1
print(total_time)

我们的时间应该不能确定为一个固定的值,我们现在可以加入random模块来实现时间的随机性。

python 复制代码
import random
import time

sleep_time=random.randint(0,2)+random.random
print(sleep_time)
time.sleep(sleep_time)

现在我们可以把爬虫和时间间隔结合在一起了:

python 复制代码
import requests
from bs4 import BeautifulSoup
import time
import random

link=''

def scrap(link):
    headers={'User-Agent':''}
    r=requests.get(link,headers=headers)
    heml=r.text
    soup=BeautifulSoup(html,"ixml")
    return soup
soup=scrap(link)
title_list=soup.find_all("h1",class_="post-title")
for eachone in title_list:
    url=eachone.a['href']
    print('开始爬取:',url)
    soup_art=scrap(url)
    title=soup_art.find("h1",class_="view-title").text.strip()
    print('标题:',title)
    sleep_time=random.randint(0,2)+random.random()
    print('开始休息:',sleep_time,'秒')
    time.sleep(sleep_time)

我们可以把爬取的放入文件里面

相关推荐
jerryinwuhan1 小时前
基于各城市站点流量的复合功能比较
开发语言·php
曦月逸霜1 小时前
啥是RAG 它能干什么?
人工智能·python·机器学习
2301_769340672 小时前
如何在 Vuetify 中可靠捕获 Chip 关闭事件(包括键盘触发).txt
jvm·数据库·python
迈巴赫车主2 小时前
Java基础:list、set、map一遍过
java·开发语言
南 阳3 小时前
Python从入门到精通day66
开发语言·python
m0_596749094 小时前
JavaScript中手动实现一个new操作符的底层逻辑
jvm·数据库·python
DTAS尺寸公差分析软件4 小时前
DTAS3D v13.0 三维尺寸公差分析软件可申请试用
python·尺寸公差分析·三维公差分析·公差仿真软件·尺寸链计算
DTAS尺寸公差分析软件4 小时前
DTAS 3D公差分析软件最新版本介绍
python·3d·尺寸公差分析·尺寸链计算·尺寸工程·尺寸链校核软件·公差仿真分析
PieroPc4 小时前
CAMWATCH — 局域网摄像头监控系统 Fastapi + html
前端·python·html·fastapi·监控
feasibility.4 小时前
反爬十层妖塔:现代爬虫攻防的立体战争
爬虫·python·科技·scrapy·rust·go·硬件