需求:
爬取的网址是:上海二手房房源_上海二手房出售|买卖|交易信息(上海链家)
爬取的内容是:标题,房屋位置,房屋信息,价格(总价,真实价格),房屋标签
使用到的库:pymysql(作为数据存储方式),request(发送请求),BeautifulSoup(用于网页解析)
思路:
打开所要爬取的网页,进入网页源代码模式,按照自己的需求找到爬取的数据内容所在位置,接下来使用解析库对网页进行解析,得到所需要的数据内容。得到数据之后使用mysql作为数据存储方式将得到的数据进行保存,最后进行查看验证。
具体步骤:
1首先进入所要爬取的网址,打开该网页的源代码(F12或者鼠标右击单击检查),观察所要爬取的数据内容的代码特征
2..按照代码特征,在源代码中检索到需要爬取的数据内容;
3.将得到的数据使用mysql进行保存处理,保存时设置一些提示信息
4.最后运行程序,爬取数据
5.进入mysql进行查看,看数据是否已经保存成功
具体操作:
首先使用python的第三方库request按照网址获取该网页的所有信息,确保后面对代码进行检索的时候,不是空数据
确定有数据之后,按照数据特征对数据进行提取
提取到数据之后,对数据进行存储,使用mysql
启动程序函数
运行程序,并打开mysql对数据进行查看,是否已经保存成功。
完整代码如下:
import pymysql
import requests
from bs4 import BeautifulSoup
class LianJiaSpider():
connect = pymysql.connect(host='localhost', user='root', passwd='123456', database='test')
mycursor = connect.cursor()
#初始化
def __init__(self):
self.url='https://sh.lianjia.com/ershoufang/pg{0}/'
self.headers={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36 Edg/109.0.1518.70'}
#发送请求
def send_request(self,url):
resp = requests.get(url,headers=self.headers)
if resp.status_code==200:
return resp
#解析网页
def parse_html(self,resp):
#先获取所要解析的网页内容(text)
html = resp.text
#使用四种方式中的一种进行解析网页,这里使用的是BeautifulSoup
bs = BeautifulSoup(html, 'lxml')
ul = bs.find('ul', class_="sellListContent")
ul_list = ul.find_all('li')
lst = []
for item in ul_list:
title = item.find('div', class_='title').text
positionInfo = item.find('div', class_="positionInfo").text
houseInfo = item.find('div', class_="houseInfo").text
total_price = item.find('div', class_="totalPrice totalPrice2").text
unitPrice = item.find('div', class_="unitPrice").text
tag = item.find('div', class_='tag').text
lst.append((title,positionInfo,houseInfo,total_price,unitPrice,tag))
# print(lst)
# print(len(ul_list))
self.save(lst)
#保存数据
def save(self,lst):
sql = 'insert into lianjia_sql (title,positionInfo,houseInfo,total_price,unitPrice,tag) values (%s,%s,%s,%s,%s,%s)'
#执行操作
self.mycursor.executemany(sql,lst)
#进行执行操作的时候要注意需要插入的数据量,如果是列表或者元组需要使用executemany,如果是单条就使用execute
#提交数据
self.connect.commit()
#输出提醒语句
print(self.mycursor.rowcount,'插入成功!')
#启动
def start(self):
for i in range(1,10):
full_url = self.url.format(i)
# print(full_url)
resp = self.send_request(full_url)
# print(resp.text)
self.parse_html(resp)
#主函数
if __name__ == '__main__':
lianjia = LianJiaSpider()
lianjia.start()