广告
返回顶部
首页 > 资讯 > 后端开发 > Python >python3爬虫-通过requests
  • 629
分享到

python3爬虫-通过requests

爬虫requests 2023-01-31 00:01:30 629人浏览 安东尼

Python 官方文档:入门教程 => 点击学习

摘要

import requests from fake_useragent import UserAgent from lxml import etree from urllib.parse import urljoin import py

import requests
from fake_useragent import UserAgent
from lxml import etree
from urllib.parse import urljoin
import pyMysql
import time

ua = UserAgent()


class MyException(Exception):

    def __init__(self, status, msg):
        self.status = status
        self.msg = msg
        super().__init__()


class XiCi:

    def __init__(self):
        self.session = requests.Session()
        self.session.headers = {
            "User-Agent": ua.random,
            "Host": "www.xicidaili.com"
        }
        self.conn = pymysql.connect(host="127.0.0.1",
                                    port=3306,
                                    user="root",
                                    db="proxies")
        self.cursor = self.conn.cursor(cursor=pymysql.cursors.DictCursor)

    def get_page_html(self, api):
        '''通过get方法请求网页'''
        response = self.session.get(url=api, headers=self.session.headers)
        if response.status_code == 200:
            return response

    def __html_to_etree(self, html):
        '''将html源码转为xml'''
        return etree.HTML(html)

    def get_next_page_url(self, response):
        '''拿到下一页的url'''
        selector = self.__html_to_etree(response.text)
        try:
            next_page_url = selector.xpath("//a[@class='next_page']/@href")[0]
            next_page_url = urljoin(response.url, next_page_url)
            return next_page_url
        except IndexError:
            raise MyException(1000, "爬取完毕")

    def __get_proxies_info(self, response):
        '''获取到爬取的代理信息'''
        selector = self.__html_to_etree(response.text)
        tr_ele_list = selector.xpath("//*[@id='ip_list']//tr")
        for tr in tr_ele_list:
            ip = tr.xpath("td[2]/text()")
            if not ip:
                continue
            ip = ip[0]
            port = tr.xpath("td[3]/text()")[0]
            type = tr.xpath("td[6]/text()")[0]
            yield [ip, port, type]

    def __detect_availability(self, data):
        '''拿到爬取的数据,检测代理是否可以使用'''
        https_api = "Https://icanhazip.com/"
        http_api = "http://icanhazip.com/"
        ip = data[0]
        port = data[1]
        type = data[2]
        proxies = {type.lower(): "{}://{}:{}".fORMat(type.lower(), ip, port)}
        try:
            if type.upper() == "HTTPS":
                requests.get(https_api, headers={"User-Agent": ua.random}, proxies=proxies, timeout=3)
            else:
                requests.get(http_api, headers={"User-Agent": ua.random}, proxies=proxies, timeout=3)
            return True
        except Exception:
            return False

    def get_usable_proxies_ip(self, response):
        '''获取到可用的代理ip'''
        res = self.__get_proxies_info(response)
        for data in res:
            if self.__detect_availability(data):
                self.save_to_db(data)

    def save_to_db(self, data):
        '''保存到数据库'''
        sql = 'insert into proxies_table(ip,port,type) values(%s,%s,%s);'
        print(data)
        self.cursor.execute(sql, data)
        self.conn.commit()

    def run(self, api):
        '''启动入口'''
        page = 1
        while True:
            print("爬取第{}页数据...".format(page))
            response = self.get_page_html(api)
            self.get_usable_proxies_ip(response)
            try:
                api = self.get_next_page_url(response)
            except MyException as e:
                if e.status == 1000:
                    print(e.msg)
                    break
            page += 1
            time.sleep(3)

    def __del__(self):
        self.conn.close()


if __name__ == '__main__':
    api = "https://www.xicidaili.com/nn"
    xici = XiCi()
    xici.run(api)

 

--结束END--

本文标题: python3爬虫-通过requests

本文链接: https://www.lsjlt.com/news/182152.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • python3爬虫-通过requests
    import requests from fake_useragent import UserAgent from lxml import etree from urllib.parse import urljoin import py...
    99+
    2023-01-31
    爬虫 requests
  • Python3 爬虫 requests
    刚学Python爬虫不久,迫不及待的找了一个网站练手,新笔趣阁:一个小说网站。 安装Python以及必要的模块(requests,bs4),不了解requests和bs4的同学可以去官网看个大概之后再回来看教程 刚开始写爬虫的小白都有...
    99+
    2023-01-31
    爬虫 requests
  • python3爬虫-通过selenium
    from selenium import webdriver from selenium.common.exceptions import NoSuchElementException from selenium.webdriver.c...
    99+
    2023-01-31
    爬虫 selenium
  • Python3爬虫利器:requests怎么安装
    这篇文章主要介绍了Python3爬虫利器:requests怎么安装,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。python可以做什么Python是一种编程语言,内置了许多有...
    99+
    2023-06-14
  • Requests爬虫
      之前写过一个urllib的爬虫方法,这个库是python内建的,从那篇文章也可以看到,使用起来很繁琐。现在更流行的一个爬虫库就是requests,他是基于urllib3封装的,也就是将之前比较繁琐的步骤封装到一块,更适合人来使用。 ...
    99+
    2023-01-30
    爬虫 Requests
  • python: 爬虫利器requests
    requests并不是系统自带的模块,他是第三方库,需要安装才能使用 闲话少说,来,让我们上代码:简单的看一下效果: import requests requests = requests.session() headers = { ...
    99+
    2023-01-31
    爬虫 利器 python
  • 【Python3爬虫】拉勾网爬虫
    一、思路分析:在之前写拉勾网的爬虫的时候,总是得到下面这个结果(真是头疼),当你看到下面这个结果的时候,也就意味着被反爬了,因为一些网站会有相应的反爬虫措施,例如很多网站会检测某一段时间某个IP的访问次数,如果访问频率太快以至于看起来不像正...
    99+
    2023-01-31
    爬虫 拉勾网
  • 通过淘宝数据爬虫学习python scrapy requests与response对象
    目录Request 对象Response 对象ItemPipelineLinkExtractor 提取链接爬虫编码时间Request 对象 在 scrapy 中 Request 对象...
    99+
    2022-11-11
  • Requests什么的通通爬不了的Python超强反爬虫方案!
    目录一、前言二、反爬虫三、措施一、前言 一个非常强的反爬虫方案 —— 禁用所有 HTTP 1.x 的请求! 现在很多爬虫库其实对 HTTP/2.0 支持得不好,比如大名鼎鼎...
    99+
    2022-11-12
  • Python爬虫之Requests库的基
    1 import requests 2 response = requests.get('http://www.baidu.com/') 3 print(type(response)) 4 print(response....
    99+
    2023-01-30
    爬虫 Python Requests
  • requests-html爬虫利器介绍
    爬虫用的最多的包无非就是requests, urllib,然后再利用pyquery或者bs4,xpath再去整理提取需要的目标数据。在requests-html里面只需要一步就可以完成而且可以直接进行js渲染.requests的作者Kenn...
    99+
    2023-01-30
    爬虫 利器 requests
  • Python3网络爬虫实战-17、爬虫基
    爬虫,即网络爬虫,我们可以把互联网就比作一张大网,而爬虫便是在网上爬行的蜘蛛,我们可以把网的节点比做一个个网页,爬虫爬到这就相当于访问了该页面获取了其信息,节点间的连线可以比做网页与网页之间的链接关系,这样蜘蛛通过一个节点后可以顺着节点连线...
    99+
    2023-01-31
    爬虫 实战 网络
  • Python3网络爬虫实战-11、爬虫框
    ScrapySplash 是一个 Scrapy 中支持 JavaScript 渲染的工具,本节来介绍一下它的安装方式。ScrapySplash 的安装分为两部分,一个是是 Splash 服务的安装,安装方式是通过 Docker,安装之后会...
    99+
    2023-01-31
    爬虫 实战 网络
  • Python3网络爬虫实战-15、爬虫基
    在写爬虫之前,还是需要了解一些爬虫的基础知识,如 HTTP 原理、网页的基础知识、爬虫的基本原理、Cookies 基本原理等。 那么本章内容就对一些在做爬虫之前所需要的基础知识做一些简单的总结。 在本节我们会详细了解 HTTP 的基本原理...
    99+
    2023-01-31
    爬虫 实战 网络
  • Python3网络爬虫(十一):爬虫黑科
    原文链接: Jack-Cui,http://blog.csdn.net/c406495762 运行平台: Windows Python版本: Python3.x IDE: Sublime text3 1 前言 近期,有些朋友问我一些关...
    99+
    2023-01-31
    爬虫 网络
  • Python3网络爬虫实战-10、爬虫框
    我们直接用 Requests、Selenium 等库写爬虫,如果爬取量不是太大,速度要求不高,是完全可以满足需求的。但是写多了会发现其内部许多代码和组件是可以复用的,如果我们把这些组件抽离出来,将各个功能模块化,就慢慢会形成一个框架雏形,久...
    99+
    2023-01-31
    爬虫 实战 网络
  • 【Python3爬虫】常见反爬虫措施及解
    这一篇博客,是关于反反爬虫的,我会分享一些我遇到的反爬虫的措施,并且会分享我自己的解决办法。如果能对你有什么帮助的话,麻烦点一下推荐啦。   UserAgent中文名为用户代理,它使得服务器能够识别客户使用的操作系统及版本、CPU 类...
    99+
    2023-01-30
    爬虫 措施 常见
  • python3爬虫之开篇
    写在前面的话:   折腾爬虫也有一段时间了,从一开始的懵懵懂懂,到现在的有一定基础,对于这一路的跌跌撞撞,个人觉得应该留下一些文字性的东西,毕竟好记性不如烂笔头,而且毕竟这是吃饭的家伙,必须用心对待才可以,从今天起,我将会把关于爬虫的东西...
    99+
    2023-01-30
    爬虫 开篇
  • Python3 爬虫 scrapy框架
    上次用requests写的爬虫速度很感人,今天打算用scrapy框架来实现,看看速度如何。 第一步,安装scrapy,执行一下命令 pip install Scrapy 第二步,创建项目,执行一下命令 scrapy startproje...
    99+
    2023-01-31
    爬虫 框架 scrapy
  • Python爬虫Requests库如何使用
    本篇内容主要讲解“Python爬虫Requests库如何使用”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“Python爬虫Requests库如何使用”吧!1、安装 requests 库因为学习过...
    99+
    2023-07-06
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作