如何反反爬虫

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

import requests
r =requests.get('网页网址')
print(r.requests.headers)

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

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

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

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

import time 
t1=time.time()
time.sleep(2)
t2=time.time()
total_time=t2-t1
print(total_time)

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

import random
import time

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

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

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)

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

相关推荐

  1. 如何爬虫

    2024-04-02 07:52:02       15 阅读
  2. 爬虫】User-Agent爬虫

    2024-04-02 07:52:02       24 阅读
  3. python爬虫04-常见

    2024-04-02 07:52:02       35 阅读
  4. Python 爬虫:Spring Boot 爬虫的成功案例

    2024-04-02 07:52:02       8 阅读

最近更新

  1. 玩转springboot之springboot项目监测

    2024-04-02 07:52:02       0 阅读
  2. 【LeetCode】每日一题:跳跃游戏 II

    2024-04-02 07:52:02       0 阅读
  3. Python面试题: 如何在 Python 中实现一个线程池?

    2024-04-02 07:52:02       1 阅读
  4. js时间转成xx前

    2024-04-02 07:52:02       1 阅读
  5. stm32基本定时器

    2024-04-02 07:52:02       1 阅读
  6. Kithara常见问题解答

    2024-04-02 07:52:02       1 阅读
  7. 数学,LeetCode 3102. 最小化曼哈顿距离

    2024-04-02 07:52:02       1 阅读
  8. Linux C++ 044-设计模式简介

    2024-04-02 07:52:02       1 阅读

热门阅读

  1. Docker环境安装Postgresql数据库Posrgresql 15.6

    2024-04-02 07:52:02       14 阅读
  2. HTTPS工作原理

    2024-04-02 07:52:02       16 阅读
  3. 浅述HTML5的离线存储

    2024-04-02 07:52:02       13 阅读
  4. MongoDB聚合运算符:$lt

    2024-04-02 07:52:02       17 阅读
  5. 云计算概述报告

    2024-04-02 07:52:02       15 阅读
  6. 在课堂中使用 ChatGPT 的 80 个方式(下)

    2024-04-02 07:52:02       17 阅读
  7. 上海大学通信829考研踩坑记录

    2024-04-02 07:52:02       15 阅读