教程集 www.jiaochengji.com
教程集 >  脚本编程  >  php  >  正文 Python什么时候用到字典

Python什么时候用到字典

发布时间:2020-10-31   编辑:jiaochengji.com
教程集为您提供Python什么时候用到字典等资源,欢迎您收藏本站,我们将为您提供最新的Python什么时候用到字典资源
字典(Dictionary)在Python中是一种可变的容器模型,它是通过一组键(key)值(value)对组成,这种结构类型通常也被称为映射,或者叫关联数组,也有叫哈希表的。每个key-value之间用“:”隔开,每组用“,”分割,整个字典用“{}”括起来。

凡是用到键值对的地方,就可以用字典。爬虫中的headers都可以用到字典(推荐学习:Python视频教程)

# coding:utf-8

import requests
from bs4 import BeautifulSoup


class SpiderProxy(object):
    #Python版本为2.7以上
    headers = {
        "Host": "www.xicidaili.com",
        "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:47.0) Gecko/20100101 Firefox/47.0",
        "Accept": "text/html,application/xhtml xml,application/xml;q=0.9,*/*;q=0.8",
        "Accept-Language": "en-US,en;q=0.5",
        "Accept-Encoding": "gzip, deflate",
        "Referer": "http://www.xicidaili.com/wt/1",
    }

    def __init__(self, session_url):
        self.req = requests.session()
        self.req.get(session_url)

    def get_pagesource(self, url):
        html = self.req.get(url, headers=self.headers)
        return html.content

    def get_all_proxy(self, url, n):
        data = []
        for i in range(1, n):
            html = self.get_pagesource(url   str(i))
            soup = BeautifulSoup(html, "lxml")

            table = soup.find('table', id="ip_list")
            for row in table.findAll("tr"):
                cells = row.findAll("td")
                tmp = []
                for item in cells:

                    tmp.append(item.find(text=True))
                data.append(tmp[1:3])
        return data

session_url = 'http://www.xicidaili.com/wt/1'
url = 'http://www.xicidaili.com/wt/'
p = SpiderProxy(session_url)
proxy_ip = p.get_all_proxy(url, 10)
for item in proxy_ip:
    if item:
        print item

更多Python相关技术文章,请访问Python教程栏目进行学习!

以上就是Python什么时候用到字典的详细内容,更多请关注教程集其它相关文章!

  • 本文原创发布教程集,转载请注明出处,感谢您的尊重!
  • 您可能感兴趣的文章:
    Python什么时候用到字典
    怎么使用python字典中fromkeys方法?
    python字典中fromkeys方法使用教程
    在python中使用字典时用什么隔开
    python字典的特点是什么?怎么应用?
    Python:星号变量的用法(单、双星号)
    为什么大佬的类都有__slots__?
    python3字典中的fromkeys()函数用法
    Flask钩子函数是什么
    Python字典能用来干什么

    [关闭]
    ~ ~