python爬虫

好久没写Python了, 所以就来写个爬虫玩玩, 就当练习下, 来爬一爬赶集网上的房源数据

首先导入模块

这是要说下, 模块主要是为了我们方便分析爬到的网页等数据, 从而避免我们去自己手写一些 恶心的 正则表达式.

而具体的模块的用法, 我这里就不介绍了, 可以看官方文档哈.

话补多少, 直接看代码吧!

这只是个简单的示例哦! 所以就直接在主函数main中将一些参数写死了.

我就不一一解释了, 基本都有注释哈

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# coding:utf-8
from bs4 import BeautifulSoup
from urlparse import urljoin
import requests
import csv
import html5lib

URL = "http://bj.ganji.com/fang1/o{page}p{price}/"
ADDR = "http://bj.ganji.com/"

if __name__ == '__main__':
start_page = 1 # 要爬取的开始页
end_page = 10 # 要爬取的结束页
price = 5 # 爬取价格为5千左右的
# 创建一个csv文件存放即将爬到的数据.
with open('ganji.csv', 'wb') as f:
csv_writer = csv.writer(f, delimiter=',')
print('start .....开始爬虫')
while start_page <= end_page:
start_page += 1
print('get:{0}'.format(URL.format(page=start_page, price=price)))
response = requests.get(URL.format(page=start_page, price=price))
# 第一个参数是要读取得html文本, 第二个参数是使用哪种解析器(默认的html.parser)
html = BeautifulSoup(response.text, 'html.parser')
# 获取房源信息
house_list = html.select('.f-list > .f-list-item > .f-list-item-wrap')
if not house_list:
break
for house in house_list:
house_title = house.select('.title > a')[0].string.strip().encode('utf-8')
house_addr = house.select('.address > .area > a')[-1].string.strip().encode('utf-8')
house_price = house.select('.info > .price > .num')[0].string.strip().encode('utf-8')
house_url = urljoin(ADDR, house.select('.title > a')[0]['href'])
csv_writer.writerow([house_price, house_addr, house_title, house_url, ' '])
print('end ....结束爬虫')

效果图