Python编程:搭建一个爬虫代理池

简介: Python编程:搭建一个爬虫代理池

分析目标页面

爬取代理ip的地址:http://www.xicidaili.com/

image.png

页面分析:

ip在table(id=ip_list)中按照行存放,只要遍历table对象中每个行 tr ,就可以取到每行的数据,再取出每个列 td 中的内容就可以,总的来说比较简单。


代码示例

import requests
from bs4 import BeautifulSoup
import xlsxwriter
import sqlite3
import time
def get_html_text(url):
    """获取网页,返回文本格式"""
    try:
        headers = {
            "User-Agent":"""Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 
            (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36"""
            }
        r = requests.get(url, headers=headers)
        r.raise_for_status()  # 状态不是200,抛出异常
        r.encoding = r.apparent_encoding  # 编码
        return r.text
    except:
        return "产生异常"
def get_proxies():
    """获取代理ip,以[{},{}]形式返回"""
    url = "http://www.xicidaili.com/"
    html = get_html_text(url)
    soup = BeautifulSoup(html, "html.parser")
    ip_list = soup.find(id="ip_list")
    proxies = []
    for tr in ip_list.find_all("tr"):
        try:
            proxy = {}
            # ["代理IP地址", "端口", "服务器地址", "是否匿名", "类型", "存活时间", "验证时间"]
            tds = tr.find_all("td")
            ip = tds[1].string
            port = tds[2].string
            addr = tds[3].string
            anonymous = tds[4].string
            typ = tds[5].string
            alive = tds[6].string
            check = tds[7].string
            proxy["ip"] = ip
            proxy["prot"] = port
            proxy["addr"] = addr
            proxy["anonymous"] = anonymous
            proxy["type"] = typ
            proxy["alive"] = alive
            proxy["check"] = check
            proxies.append(proxy)
        except:
            continue
    return proxies
def save_list_to_xlsx(lst):
    # 将列表数据保存到excel表格中,不推荐
    # 表头
    titles = ["代理IP地址", "端口", "服务器地址", "是否匿名", "类型", "存活时间", "验证时间"]
    # 新建工作薄
    book = xlsxwriter.Workbook("ip_list.xlsx")
    sheet = book.add_worksheet("sheet1")
    row = 0  # 行号
    col = 0  # 列号
    # 表头写入excel
    for title in titles:
        sheet.write(row, col, title)
        col += 1
    row += 1
    # 写入每条记录
    for dct in lst:
        print(dct)
        sheet.write(row, 0, dct.get("ip"))
        sheet.write(row, 1, dct.get("prot"))
        sheet.write(row, 2, dct.get("addr"))
        sheet.write(row, 3, dct.get("anonymous"))
        sheet.write(row, 4, dct.get("type"))
        sheet.write(row, 5, dct.get("alive"))
        sheet.write(row, 6, dct.get("check"))
        row += 1
    book.close()
    return row
class Database(object):
    """连接数据库"""
    def __init__(self, name):
        self.name = name
        self.conn = sqlite3.connect(self.name)
        self.cursor = self.conn.cursor()
    def create_table(self, tablename):
        """创建工作表"""
        self.tablename = tablename
        sql = """create table if not exists %s(
            "id" integer primary key autoincrement,
            "ip" text,
            "port" integer,
            "addr" text,
            "anonymous" text,
            "type" text,
            "alive" text,
            "check" text,
            "status" integer default 1
            )"""%self.tablename
        self.cursor.execute(sql)
    def insert(self, data):
        """插入数据"""
        self.cursor.execute("""insert into ip_list("ip", "port", "addr", "anonymous", 
            "type", "alive", "check")values(?,?,?,?,?,?,?)""", data)
        self.conn.commit()
    def get_random_ip(self):
        """随机获取一个ip"""
        sql = "select ip, port from %s where state!=0 order by random() limit 1"%(self.tablename)
        self.cursor.execute(sql)
        for ip, port in self.cursor.fetchall():
            # print("ip:", ip, "port:", port)
            if self.verify_ip(ip, port): # 验证ip
                return (ip, port)
            else:
                return get_random_ip()
    def verify_ip(self, ip, port):
        """验证ip有效性"""
        http_url = "http://www.baidu.com"
        proxy_url = "https://{}:{}".format(ip, port)
        proxies = {
            "https": proxy_url
        }
        try:
            r = requests.get(http_url, proxies=proxies)
        except:
            self.delete_ip(ip)
            return False
        else:
            # code [200,300)之间则为有效的
            if r.status_code >=200 or r.status_code<300:
                return True
            else:
                self.delete_ip(ip)
                return False
    def delete_ip(self, ip):
        """删除ip记录"""
        # sql = "delete from %s where ip = %s"% (self.tablename, ip)
        sql = "update %s set status=0 where ip =%s"%(self.tablename, ip)
        self.cursor.execute(sql)
        self.conn.commit()
    def __del__(self):
        """释放数据库连接"""
        self.cursor.close()
        self.conn.close()
def add_list_to_database(lst):
    """插入到数据库"""
    database = Database("ip_pool.db")
    count = 0  # 计数
    database.create_table("ip_list")
    for dct in lst:
        data = (dct.get("ip"), dct.get("prot"), dct.get("addr"), dct.get("anonymous"), 
            dct.get("type"), dct.get("alive"), dct.get("check"))
        database.insert(data)
        count += 1
    return count
if __name__ == '__main__':
    # 获取代理ip并存入数据库
    proxies = get_proxies()
    ret = add_list_to_database(proxies)
    print(ret)
    # 测试ip可用性
    database = Database("ip_pool.db")
    database.create_table("ip_list")
    for i in range(100):
        ip, port = database.get_random_ip()
        print(ip, port)

参考:

《小白动手搭建一个简单爬虫代理池》

《学会最简单的数据库|看完这7招就够了》

《SQLite 教程》

http://www.runoob.com/sqlite/sqlite-tutorial.html

《Beautiful Soup 4.2.0 文档》

https://www.crummy.com/software/BeautifulSoup/bs4/doc.zh/#id5

《requests快速上手》

http://cn.python-requests.org/zh_CN/latest/user/quickstart.html

相关文章
|
1天前
|
数据采集 存储 数据挖掘
深入剖析 Python 爬虫:淘宝商品详情数据抓取
深入剖析 Python 爬虫:淘宝商品详情数据抓取
|
4天前
|
存储 数据采集 数据库
Python爬虫实战:股票分时数据抓取与存储
Python爬虫实战:股票分时数据抓取与存储
|
23天前
|
存储 缓存 Java
Python高性能编程:五种核心优化技术的原理与Python代码
Python在高性能应用场景中常因执行速度不及C、C++等编译型语言而受质疑,但通过合理利用标准库的优化特性,如`__slots__`机制、列表推导式、`@lru_cache`装饰器和生成器等,可以显著提升代码效率。本文详细介绍了这些实用的性能优化技术,帮助开发者在不牺牲代码质量的前提下提高程序性能。实验数据表明,这些优化方法能在内存使用和计算效率方面带来显著改进,适用于大规模数据处理、递归计算等场景。
58 5
Python高性能编程:五种核心优化技术的原理与Python代码
|
30天前
|
数据采集 JSON 数据格式
Python爬虫:京东商品评论内容
京东商品评论接口为商家和消费者提供了重要工具。商家可分析评论优化产品,消费者则依赖评论做出购买决策。该接口通过HTTP请求获取评论内容、时间、点赞数等数据,支持分页和筛选好评、中评、差评。Python示例代码展示了如何调用接口并处理返回的JSON数据。应用场景包括产品优化、消费者决策辅助、市场竞争分析及舆情监测。
|
1月前
|
数据采集 供应链 API
Python爬虫与1688图片搜索API接口:深度解析与显著收益
在电子商务领域,数据是驱动业务决策的核心。阿里巴巴旗下的1688平台作为全球领先的B2B市场,提供了丰富的API接口,特别是图片搜索API(`item_search_img`),允许开发者通过上传图片搜索相似商品。本文介绍如何结合Python爬虫技术高效利用该接口,提升搜索效率和用户体验,助力企业实现自动化商品搜索、库存管理优化、竞品监控与定价策略调整等,显著提高运营效率和市场竞争力。
89 3
|
2月前
|
Python
[oeasy]python055_python编程_容易出现的问题_函数名的重新赋值_print_int
本文介绍了Python编程中容易出现的问题,特别是函数名、类名和模块名的重新赋值。通过具体示例展示了将内建函数(如`print`、`int`、`max`)或模块名(如`os`)重新赋值为其他类型后,会导致原有功能失效。例如,将`print`赋值为整数后,无法再用其输出内容;将`int`赋值为整数后,无法再进行类型转换。重新赋值后,这些名称失去了原有的功能,可能导致程序错误。总结指出,已有的函数名、类名和模块名不适合覆盖赋新值,否则会失去原有功能。如果需要使用类似的变量名,建议采用其他命名方式以避免冲突。
52 14
|
2月前
|
数据采集 存储 缓存
如何使用缓存技术提升Python爬虫效率
如何使用缓存技术提升Python爬虫效率
|
2月前
|
数据采集 Web App开发 监控
Python爬虫:爱奇艺榜单数据的实时监控
Python爬虫:爱奇艺榜单数据的实时监控
|
2月前
|
分布式计算 大数据 数据处理
技术评测:MaxCompute MaxFrame——阿里云自研分布式计算框架的Python编程接口
随着大数据和人工智能技术的发展,数据处理的需求日益增长。阿里云推出的MaxCompute MaxFrame(简称“MaxFrame”)是一个专为Python开发者设计的分布式计算框架,它不仅支持Python编程接口,还能直接利用MaxCompute的云原生大数据计算资源和服务。本文将通过一系列最佳实践测评,探讨MaxFrame在分布式Pandas处理以及大语言模型数据处理场景中的表现,并分析其在实际工作中的应用潜力。
116 2
|
2月前
|
Unix Linux 程序员
[oeasy]python053_学编程为什么从hello_world_开始
视频介绍了“Hello World”程序的由来及其在编程中的重要性。从贝尔实验室诞生的Unix系统和C语言说起,讲述了“Hello World”作为经典示例的起源和流传过程。文章还探讨了C语言对其他编程语言的影响,以及它在系统编程中的地位。最后总结了“Hello World”、print、小括号和双引号等编程概念的来源。
126 80

推荐镜像

更多