如何反反爬虫

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

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)

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

相关推荐
通信仿真实验室22 分钟前
(10)MATLAB莱斯(Rician)衰落信道仿真1
开发语言·matlab
勿语&25 分钟前
Element-UI Plus 暗黑主题切换及自定义主题色
开发语言·javascript·ui
belldeep1 小时前
python:reportlab 将多个图片合并成一个PDF文件
python·pdf·reportlab
吾爱星辰4 小时前
Kotlin 处理字符串和正则表达式(二十一)
java·开发语言·jvm·正则表达式·kotlin
ChinaDragonDreamer4 小时前
Kotlin:2.0.20 的新特性
android·开发语言·kotlin
FreakStudio4 小时前
全网最适合入门的面向对象编程教程:56 Python字符串与序列化-正则表达式和re模块应用
python·单片机·嵌入式·面向对象·电子diy
IT良4 小时前
c#增删改查 (数据操作的基础)
开发语言·c#
丶21364 小时前
【CUDA】【PyTorch】安装 PyTorch 与 CUDA 11.7 的详细步骤
人工智能·pytorch·python
Kalika0-05 小时前
猴子吃桃-C语言
c语言·开发语言·数据结构·算法
_.Switch5 小时前
Python Web 应用中的 API 网关集成与优化
开发语言·前端·后端·python·架构·log4j