python爬取淘宝评论存储mysql_python笔记--爬取链家二手房成交量并存储到MySQL

本文介绍了如何使用Python爬取链家网站上的二手房成交数据,并将数据存储到MySQL数据库中。首先,通过requests库发送HTTP请求获取网页内容,然后使用BeautifulSoup解析HTML,提取所需数据如房屋标题、描述、总价等。最后,利用mysql.connector连接数据库,将数据插入到指定表中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

3.逐渐填充补全代码

import requests

from bs4 import BeautifulSoup

import mysql.connector  # 连接数据库class LianJiaSpider():

# host:主机,user:用户名,passwd:密码,auth_plugin:防止报错    mydb = mysql.connector.connect(host='localhost', user='root', passwd='密码', database='python_test', auth_plugin='mysql_native_password')

print('获取连接对象,防止报错')

# cursor:指针    mycursor = mydb.cursor()

# 初始化请求的方法,注意不要拼写错误    def __init__(self):

# 找到网页,{0}:格式化请求        self.url = 'https://bj.lianjia.com/chengjiao/pg{0}/'        print('获取url')

# 伪装成浏览器        self.headers = {'User-Agent': 'Mozilla/5.0 (s NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36 Edg/88.0.705.63'}

print('获取请求头,进行伪装')

# 发送请求的方法    def send_request(self, url):

# 发送请求        resp = requests.get(url, headers=self.headers)

print('获取响应结果')

if resp.status_code == 200:

return resp

print('如果成功获取响应,返回resp')

# 解析HTML获取有用数据    def parse_content(self, resp):

# 获取并解析数据        # :param resp:相应结果        lst = []

html = resp.text

print('获取响应的html')

# 第一个参数是要解析的内容,第二个参数是解析器        bs = BeautifulSoup(html, 'html.parser')

ul = bs.find('ul', class_='sellListContent')

print('查找名称为cellListContent的ul')

li_list = ul.find_all('li')

print('在ul中获取所有的li标签')

# 遍历列表        for item in li_list:

title = item.find('div', class_='title')

title_t = title.text if title!=None else ''            print('找标题')

house_info = item.find('div', class_='houseInfo')

house_it = house_info.text if house_info!=None else ''            print('房屋描述')

total_price = item.find('div', class_='totalPrice')

total_pt = total_price.text if total_price!=None else ''            print('总价')

position_info = item.find('div', class_='positionInfo')

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值