当前位置:Gxlcms > Python > Python什么时候用到字典

Python什么时候用到字典

时间:2021-07-01 10:21:17 帮助过:76人阅读

字典(Dictionary)在Python中是一种可变的容器模型,它是通过一组键(key)值(value)对组成,这种结构类型通常也被称为映射,或者叫关联数组,也有叫哈希表的。每个key-value之间用“:”隔开,每组用“,”分割,整个字典用“{}”括起来。

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

  1. # coding:utf-8
  2. import requests
  3. from bs4 import BeautifulSoup
  4. class SpiderProxy(object):
  5. #Python版本为2.7以上
  6. headers = {
  7. "Host": "www.xicidaili.com",
  8. "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:47.0) Gecko/20100101 Firefox/47.0",
  9. "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
  10. "Accept-Language": "en-US,en;q=0.5",
  11. "Accept-Encoding": "gzip, deflate",
  12. "Referer": "http://www.xicidaili.com/wt/1",
  13. }
  14. def __init__(self, session_url):
  15. self.req = requests.session()
  16. self.req.get(session_url)
  17. def get_pagesource(self, url):
  18. html = self.req.get(url, headers=self.headers)
  19. return html.content
  20. def get_all_proxy(self, url, n):
  21. data = []
  22. for i in range(1, n):
  23. html = self.get_pagesource(url + str(i))
  24. soup = BeautifulSoup(html, "lxml")
  25. table = soup.find('table', id="ip_list")
  26. for row in table.findAll("tr"):
  27. cells = row.findAll("td")
  28. tmp = []
  29. for item in cells:
  30. tmp.append(item.find(text=True))
  31. data.append(tmp[1:3])
  32. return data
  33. session_url = 'http://www.xicidaili.com/wt/1'
  34. url = 'http://www.xicidaili.com/wt/'
  35. p = SpiderProxy(session_url)
  36. proxy_ip = p.get_all_proxy(url, 10)
  37. for item in proxy_ip:
  38. if item:
  39. print item

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

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

人气教程排行