如何反反爬虫

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

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)

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

相关推荐
m0_5557629013 分钟前
Matlab 频谱分析 (Spectral Analysis)
开发语言·matlab
浪裡遊1 小时前
React Hooks全面解析:从基础到高级的实用指南
开发语言·前端·javascript·react.js·node.js·ecmascript·php
烛阴2 小时前
简单入门Python装饰器
前端·python
lzb_kkk2 小时前
【C++】C++四种类型转换操作符详解
开发语言·c++·windows·1024程序员节
好开心啊没烦恼2 小时前
Python 数据分析:numpy,说人话,说说数组维度。听故事学知识点怎么这么容易?
开发语言·人工智能·python·数据挖掘·数据分析·numpy
面朝大海,春不暖,花不开2 小时前
使用 Python 实现 ETL 流程:从文本文件提取到数据处理的全面指南
python·etl·原型模式
简佐义的博客3 小时前
破解非模式物种GO/KEGG注释难题
开发语言·数据库·后端·oracle·golang
程序员爱钓鱼3 小时前
【无标题】Go语言中的反射机制 — 元编程技巧与注意事项
开发语言·qt
失败又激情的man3 小时前
Scrapy进阶封装(第四阶段:中间件设置,动态UA,ip代理池)
爬虫·scrapy·中间件