一个简单的实例,可以采用。做的demo。
#!/usr/bin/python
# -*- coding: utf-8 -*-
# @Time : 2020/6/4 15:55
# @Author : Xuegod Teacher For
# @File : 01_get_price_test.py
# @Software: PyCharm
'''
第一步:下载所有的html
第二步:利用xpath爬取匹配
第三步:保存到mongodb数据库中
'''
import requests #pip install requests
from lxml import etree # pip install lxml
#模拟浏览器的版本信息,python 脚本 模拟浏览器
#pip install fake-useragent
from fake_useragent import UserAgent
import pymongo #pip install
IP = '127.0.0.1'
PORT = 27017
Name = 'sun'
client = pymongo.MongoClient(IP,PORT)
db = client.sun
collection = db.lanjia
#模拟浏览器的头部信息
headers = {
"User-Agent":UserAgent().random
}
base_url = 'https://bj.lianjia.com/ershoufang/pg{}/'
#todo:下载整个网页的html
def load_page(url):
'''
:param url: 页面的url地址
:return: HTML界面
'''
try:
response = requests.get(url,headers=headers)
if response.status_code == 200:
print('页面响应成功')
#返回整体的html文本str类型
return response.text
except:
print('网络请求错误')
#todo:提取我想要的数据
def parse_html(html):
'''
:param html: 整体的html界面
:return: 数据。title和price
'''
#把具体的str类型的文本办成xpath可匹配的文本
xpath_content = etree.HTML(html)
#一个界面中的30条数据list
xpath_datas = xpath_content.xpath('//*[@class="info clear"]')
for data in xpath_datas:
try:
title = data.xpath('./div[1]/a/text()')
price = data.xpath('./div[6]/div/span/text()')
#list 是可以相加的python是强类型语言
#【titl,价格,每平方价格】
data = title + price
insert_mongo(data)
except:
#停止本次循环开始下次循环
continue
def insert_mongo(data):
collection.insert_one({
'name':data[0],
'price':data[1]+'万'
})
#多个页面数据下载
def main():
for i in range(1,10):
url = base_url.format(i)
html = load_page(url)
parse_html(html)
if __name__ == '__main__':
main()
有疑问可以进行评论~
网友评论