总结常用的功能小实例,快速学习并掌握python技能

1.墨迹天气

  1. import requests
  2. from lxml.html import etree
  3. import json
  4. import time # 导入模块
  5. class MoJiWeather():
  6. def city_name(self): # 定义一个输入城市名称的函数
  7. cityname = str(input("输入城市名称:"))
  8. return cityname
  9. def search_city(city_name):# 搜索这个城市
  10. index_url = "http://tianqi.moji.com/api/citysearch/%s"%city_name # 构造查询相应城市天气的url
  11. response = requests.get(index_url)
  12. response.encoding = "utf-8"
  13. try:# 异常捕获
  14. city_id = json.loads(response.text).get('city_list')[].get('cityId')# 通过上面的url获取城市的id
  15. city_url = "http://tianqi.moji.com/api/redirect/%s"%str(city_id) # 通过城市id获取城市天气
  16. return city_url
  17. except:
  18. print('城市名输入错误')
  19. exit()
  20. def parse(city_url):# 解析函数
  21. response = requests.get(city_url)
  22. response.encoding = 'utf-8'
  23. html = etree.HTML(response.text)
  24. current_city = html.xpath("//div[@class='search_default']/em/text()")[]#    下面都是利用xpath解析的
  25. print('当前城市:'+current_city)
  26. current_kongqi = html.xpath("//div[@class='left']/div[@class='wea_alert clearfix']/ul/li/a/em/text()")[]
  27. print('空气质量:'+current_kongqi)
  28. current_wendu = html.xpath("//div[@class='left']/div[@class='wea_weather clearfix']/em/text()")[]
  29. print('当前温度:'+current_wendu+'℃')
  30. current_weather = html.xpath("//div[@class='wea_weather clearfix']/b/text()")[]
  31. print('天气状况:' + current_weather)
  32. current_shidu = html.xpath("//div[@class='left']/div[@class='wea_about clearfix']/span/text()")[]
  33. print('当前湿度:'+current_shidu)
  34. current_fengji = html.xpath("//div[@class='left']/div[@class='wea_about clearfix']/em/text()")[]
  35. print('当前风速:'+current_fengji)
  36. jingdian = html.xpath("//div[@class='right']/div[@class='near'][2]/div[@class='item clearfix']/ul/li/a/text()")
  37. print('附近景点:')
  38. for j in jingdian:
  39. print('\t\t'+j)
  40. if __name__ == '__main__':
  41. print("欢迎使用墨迹天气查询系统")
  42. city_name = MoJiWeather.city_name()
  43. city_url = MoJiWeather.search_city(city_name)
  44. MoJiWeather.parse(city_url)
  45. print("谢谢使用本查询系统")
  46. input("按任意键退出...")

2.Tiobe排行榜

  1. import json
  2. from lxml import etree
  3. from lxml.etree import ParseError
  4. import requests
  5. from requests.exceptions import RequestException
  6.  
  7. '''
  8. lxml实例应用
  9. '''
  10.  
  11. '''
  12. 获取页面数据
  13. '''
  14. def one_to_page(url):
  15. headers = {
  16. 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.62 Safari/537.36'
  17. }
  18.  
  19. try:
  20. res = requests.get(url,headers=headers)
  21. body = res.text #获取网页内容
  22. except RequestException as e:
  23. print('request is error',e)
  24.  
  25. try:
  26. html = etree.HTML(body,etree.HTMLParser())
  27. # tr 下的所有子孙节点(只获取文本数,图片资源不获取)
  28. result = html.xpath('//table[contains(@class,"table-top20")]/tbody/tr//text()')
  29.  
  30. pos =
  31. for i in range():
  32. if i == :
  33. yield result[i:]
  34. else:
  35. yield result[pos:pos+]
  36. pos +=
  37.  
  38. except ParseError as e:
  39. print(e.position)
  40.  
  41. '''
  42. 写入文件
  43. '''
  44. def write_file(data):
  45. for item in data:
  46. sul = {
  47. '2018年6月排行': item[],
  48. '2017年6排行': item[],
  49. '开发语言': item[],
  50. '评级': item[],
  51. '变化率': item[]
  52. }
  53. # with 更好处理异常情况,进行文件的关闭后续工作
  54. with open('test.txt','a',encoding='utf-8') as f:
  55. f.write(json.dumps(sul,ensure_ascii=False)+'\n')
  56. f.close()
  57. print(sul)
  58. return None
  59.  
  60. '''
  61. 主程序
  62. '''
  63. def main():
  64. url = 'https://www.tiobe.com/tiobe-index/'
  65. data = one_to_page(url)
  66. ret = write_file(data)
  67. if ret == None:
  68. print('ok')
  69.  
  70. if __name__ == '__main__':
  71. main()

3.新闻列表

  1. '''
  2. 墨迹天气文章爬虫
  3. '''
  4. import requests
  5. import json
  6. from lxml.html import etree
  7. from lxml.etree import ParseError
  8.  
  9. '''
  10. 解析页面内容
  11. '''
  12. def parseHtml(content):
  13. try:
  14. html = etree.HTML(content,etree.HTMLParser())
  15. # one = html.xpath('//ul[@class="advisory_list_item"]//text()')
  16. one = html.xpath('//ul[@class="advisory_list_item"]//li/a/@href')
  17. print(one)
  18. exit()
  19. LOOP =
  20. pos =
  21. for i in range():
  22. if i == :
  23. yield one[:LOOP]
  24. else:
  25. yield one[pos:pos+LOOP]
  26. pos += LOOP
  27.  
  28. except ParseError as e:
  29. print(e.position)
  30.  
  31. '''
  32. 写入文件
  33. '''
  34. def write_log(data):
  35. for item in data:
  36. msg = {
  37. '发文时间':item[],
  38. '文章标题':item[]
  39. }
  40. with open('moji.log','a',encoding='utf-8') as f:
  41. f.write(json.dumps(msg,ensure_ascii=False)+'\n')
  42. f.close()
  43. print(msg)
  44. return None
  45. '''
  46. 主程序
  47. '''
  48. def main():
  49.  
  50. for page in range(,):
  51. url = 'https://tianqi.moji.com/news/list/moji/{}'.format(page)
  52. res = requests.get(url)
  53. res.encoding = 'utf-8'
  54. content = parseHtml(res.text)
  55. ret = write_log(content)
  56. if ret is None:
  57. print('ok')
  58.  
  59. if __name__ == '__main__':
  60. main()

4.爬取IP

  1. import requests
  2. import re
  3. import random
  4.  
  5. from bs4 import BeautifulSoup
  6.  
  7. ua_list = [
  8. "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36",
  9. "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.75 Safari/537.36",
  10. "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.119 Safari/537.36",
  11. "Mozilla / 5.0(Windows NT 6.1;WOW64) AppleWebKit / 537.36(KHTML, likeGecko) Chrome / 45.0.2454.101Safari / 537.36"
  12. ]
  13.  
  14. def ip_parse_xici(page):
  15. """
  16.  
  17. :param page: 采集的页数
  18. :return:
  19. """
  20. ip_list = []
  21. for pg in range(, int(page)):
  22. url = 'http://www.xicidaili.com/nn/' + str(pg)
  23. user_agent = random.choice(ua_list)
  24. my_headers = {
  25. 'Accept': 'text/html, application/xhtml+xml, application/xml;',
  26. 'Accept-Encoding': 'gzip, deflate, sdch',
  27. 'Accept-Language': 'zh-CN,zh;q=0.8',
  28. 'Referer': 'http: // www.xicidaili.com/nn',
  29. 'User-Agent': user_agent
  30. }
  31. try:
  32. r = requests.get(url, headers=my_headers)
  33. soup = BeautifulSoup(r.text, 'html.parser')
  34. except requests.exceptions.ConnectionError:
  35. print('ConnectionError')
  36. else:
  37. data = soup.find_all('td')
  38. # 定义IP和端口Pattern规则
  39. ip_compile = re.compile(r'<td>(\d+\.\d+\.\d+\.\d+)</td>') # 匹配IP
  40. port_compile = re.compile(r'<td>(\d+)</td>') # 匹配端口
  41. ips = re.findall(ip_compile, str(data)) # 获取所有IP
  42.  
  43. ports = re.findall(port_compile, str(data)) # 获取所有端口
  44. check_api = "http://ip.taobao.com/service/getIpInfo2.php?ip="
  45.  
  46. for i in range(len(ips)):
  47. if i < len(ips):
  48. ip = ips[i]
  49. api = check_api + ip
  50. api_headers = {
  51. 'User-Agent': user_agent
  52. }
  53. try:
  54. response = requests.get(url=api, headers=api_headers, timeout=)
  55. print("ip:%s 可用" % ip)
  56. except Exception as e:
  57. print("此ip %s 已失效:%s" % (ip, e))
  58. del ips[i]
  59. del ports[i]
  60. ips_usable = ips
  61. ip_list += [':'.join(n) for n in zip(ips_usable, ports)] # 列表生成式
  62. print('第{}页ip采集完成'.format(pg))
  63. print(ip_list)
  64.  
  65. if __name__ == '__main__':
  66. xici_pg = input("请输入需要采集的页数:")
  67. ip_parse_xici(page=xici_pg)

python3小demo的更多相关文章

  1. selenium 3+python3.6+firefox的windows详细环境搭建以及小demo

    最近也是学习了下selenium和python,就记录了下在自己工作机上环境的搭建过程以及小demo 1,安装python3.6.1 我是去官网直接下载当前最新版的python3.6.1 官网网址为h ...

  2. 新手 gulp+ seajs 小demo

    首先,不说废话,它的介绍和作者就不在多说了,网上一百度一大堆: 我在这里只是来写写我这2天抽空对seajs的了解并爬过的坑,和实现的一个小demo(纯属为了实现,高手请绕道); 一.环境工具及安装 1 ...

  3. Nancy之基于Nancy.Hosting.Self的小Demo

    继昨天的Nancy之基于Nancy.Hosting.Aspnet的小Demo后, 今天来做个基于Nancy.Hosting.Self的小Demo. 关于Self Hosting Nancy,官方文档的 ...

  4. Nancy之基于Nancy.Owin的小Demo

    前面做了基于Nancy.Hosting.Aspnet和Nancy.Hosting.Self的小Demo 今天我们来做个基于Nancy.Owin的小Demo 开始之前我们来说说什么是Owin和Katan ...

  5. Nancy之基于Self Hosting的补充小Demo

    前面把Hosting Nancy with ASP.NET.Self Hosting Nancy和Hosting Nancy with OWIN 以demo的形式简单描述了一下. 这篇是为Self H ...

  6. [Unity3D]做个小Demo学习Input.touches

    [Unity3D]做个小Demo学习Input.touches 学不如做,下面用一个简单的Demo展示的Input.touches各项字段,有图有真相. 本项目已发布到Github,地址在(https ...

  7. Android -- 自定义View小Demo,动态画圆(一)

    1,转载:(http://blog.csdn.NET/lmj623565791/article/details/24500107),现在如下图的效果: 由上面的效果图可以看到其实是一个在一个圆上换不同 ...

  8. Win10 FaceAPI小demo开发问题汇总

    Win10 FaceAPI小demo开发问题汇总 最近使用微软牛津计划做一个小demo,使用FaceAPI做一个小应用,实现刷脸的功能.开发的过程中用到几个问题,具体如下: Stream 与IRand ...

  9. 模仿京东顶部搜索条效果制作的一个小demo

    最近模仿京东顶部搜索条效果制作的一个小demo,特贴到这里,今后如果有用到可以参考一下,代码如下 #define kScreenWidth [UIScreen mainScreen].bounds.s ...

随机推荐

  1. Java线程细节

    启动一个线程是用  run() 还是 start()?启动一个线程是调用 start()方法,启动线程并调用 run 方法 线程的基本概念.线程的基本状态以及状态之间的关系线程是进程内的并发,没有自已 ...

  2. maven国内镜像、国内外仓库(直接下载jar)

    阿里: https://maven.aliyun.com/mvn/search 官方: http://repo.maven.apache.org/maven2/ maven仓库 阿里巴巴的镜像仓库, ...

  3. 套接字I/O函数write/read writev/readv send/recv sendto/recvfrom sendmsg/recvmsg

    函数原型 read/write系原型 #include <unistd.h> ssize_t read(int fd, void *buf, size_t count); #include ...

  4. ubuntu16.04修改host上外網

    1.打开hosts文件: sudo emacs /etc/hosts 2.加入下面的内容 #chrome同步服务器 203.208.46.132 chrome.google.com203.208.46 ...

  5. LeetCode 61. 旋转链表(Rotate List)

    题目描述 给定一个链表,旋转链表,将链表每个节点向右移动 k 个位置,其中 k 是非负数. 示例 1: 输入: 1->2->3->4->5->NULL, k = 2 输出 ...

  6. [HTML辅助方法-Html.Raw()的简单应用]

    Html.Raw(); 当我们使用 文本编辑器,存入到数据库中的数据会带 html 标签,如果我们需要在前台显示存入时的相同样式,不输出为带有html标签的字符串 ,不通过富文本显示的话,可以通过ht ...

  7. 浏览器端-W3School-JavaScript:Location 对象

    ylbtech-浏览器端-W3School-JavaScript:Location 对象 1.返回顶部 1. Location 对象 Location 对象 Location 对象包含有关当前 URL ...

  8. nodejs之简单应用与运行

    1.nodejs第一个应用,入口函数为http.createServer() var http=require('http');//1.引入 http 模块 //2.用 http 模块创建服务 htt ...

  9. flum到kafka 收集数据 存储到redis 案例 (ip.txt)

    ip.scala package ip import org.apache.kafka.clients.consumer.ConsumerRecord import org.apache.kafka. ...

  10. 错误:expected initializer before "***"

    今天写了一个程序,编译时报了一个错误:expected initializer before "***"报错的语句只是程序开头的一个变量定义语句,怎么会有这样的错误呢,琢磨了半天也 ...