python爬虫1:第一个爬虫

1。python2、3的库名不同,如果版本不同记得改。

Python2.x 有这些库名可用: urlliburllib2urllib3httplibhttplib2requests
Python3.x 有这些库名可用: urlliburllib3httplib2requests

2。第一个简单的爬虫,获取链家当日房源数量

 1 #!/usr/bin/env python  
 2 # -*- coding: utf-8 -*-  
 3 # python3
 4 from urllib import request
 5 import re
 6 import time;  # 引入time模块
 7 
 8 today_date = time.strftime("%Y-%m-%d", time.localtime()) 
 9 gotpagebyte = request.urlopen("https://sz.lianjia.com/ershoufang/").read()
10 #python2里是urllib2.urlopen;此处获取到的是bytes,需要解码:
11 gotpagestr = gotpagebyte.decode('utf-8')
12 today_count_sz = re.match('.*count: (.*?),.*',gotpagestr,re.M|re.I|re.S).group(1)
13 print (today_date,today_count_sz)

3.虚拟环境。直接用root身份安装包时,对所有用户和项目起作用,有可能不同项目需要的包版本不同会冲突。因此可以设置虚拟环境,在虚拟环境中安装的包相对独立。先要安装python3-virtualenv。

在需要建立虚拟环境的目录下,运行virtualenv scraping。vfat分区会出现错误,貌似只能设置在linux分区中。

猜你喜欢

转载自www.cnblogs.com/cityfckr/p/12303945.html