字典(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教程 python编程 python使用问题
版权声明:除非特别标注,否则均为本站原创文章,转载时请以链接形式注明文章出处。
抱歉,评论功能暂时关闭!