一 、requests模块安装
pip install requests
二、get请求方式
在这里不讲任何理论的东西直接实操一个例子:获取链家网数据
1、浏览器-百度链家网-获取链家网的网址
点击链家网官网进入
进入到这个界面右键检查
可以发现需要的信息就在html源码中。
切换到网络(Nextwork)重新刷新一下网页,可以找到如下内容。
可以知道获取html的信息只需要用get请求。
记下当前页网址,进行翻页后再看网址跟之前页网址对比:
https://sz.lianjia.com/ershoufang/
https://sz.lianjia.com/ershoufang/pg2/
https://sz.lianjia.com/ershoufang/pg3/
可以发现规律是后面pg后的数字发生变化,将第一页网址加上pg1发现也能访问到第一页。所以我们最后用于get请求中的网址就应该是 : https://sz.lianjia.com/ershoufang/pg{n}/
import time
import requests
from lxml import etree
import pymongo
def get_info(url_):
res = requests.get(url_, headers=headers) # 获取到html数据
if res.ok:
# 使用lxml提取数据
parser = etree.HTMLParser(encoding="utf-8")
tree = etree.HTML(res.text, parser=parser)
for li in tree.xpath('//*[@id="content"]/div[1]/ul/li'):
title = li.xpath('div[1]/div[1]/a/text()')[0]
location = li.xpath('div[1]/div[2]/div/a[1]/text()')[0] + "-" + li.xpath('div[1]/div[2]/div/a[1]/text()')[0]
description = li.xpath('div[1]/div[3]/div/text()')[0]
date_posted = li.xpath('div[1]/div[4]/text()')[0].split("/")[1].strip()
href = li.xpath('div[1]/div[1]/a/@href')[0]
total_prices = li.xpath('div[1]/div[6]/div[1]/span/text()')[0]
unit_price = li.xpath('div[1]/div[6]/div[2]/span/text()')[0]
# 将提取的数据封装成字典方便于插入数据库
data = {
"标题": title,
"地址": location,
"描述": description,
"发布时间": date_posted,
"链接": href,
"总价/万": total_prices,
"单价": unit_price
}
collection.insert_one(data) # 将提取出来的数据插入到数据库
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36 Edg/114.0.1823.37",
}
# 连接mongodb数据库
client = pymongo.MongoClient("127.0.0.1", 27017) # 创建连接
db = client.mydb # 指定或创建数据库
collection = db.lianjia_01 # 指定或创建集合
#获取第一页到第三页数据
for i in range(1, 4):
url = f"https://cs.lianjia.com/ershoufang/pg{i}/"
get_info(url)
time.sleep(1)