python+BeautifulSoup+selenium+mysqldb完成数据抓取

本文介绍了一种使用Python进行网页数据抓取的方法,通过Selenium和BeautifulSoup实现对糯米网三亚地区特定页面的解析,并将抓取的数据存入MySQL数据库中。该过程涉及浏览器自动化控制、HTML解析及数据库操作等关键技术。
# coding=utf-8
'''
Created on 2017年2月20日

@author: chenkai
'''
import MySQLdb
import sys
from selenium import webdriver
from bs4 import BeautifulSoup
from selenium.webdriver.common.by import By
import time
from selenium.webdriver.remote import webelement
from selenium.webdriver.remote.webelement import WebElement
'''
连接数据库
'''
def getConn():
host ='127.0.0.1'
user ='root'
passwd ='123456'
port = 3306
dbcon=MySQLdb.connect(host,user,passwd,port=3306,charset="utf8")
return dbcon
def getCursor(mysqlConn):
return mysqlConn.cursor()
def closeDBConnandCur(cur,mysqlConn):
cur.close()
mysqlConn.commit() #[color=red]加上这句,关闭数据库连接前提交数据库操作[/color]
mysqlConn.close()
#连接数据库
mysqlConn=getConn()
#得道curser
cur=getCursor(mysqlConn)
#使用test数据库
cur.execute("use test")

'''
浏览器
'''
options=webdriver.ChromeOptions()
options.add_experimental_option("excludeSwitches", ["ignore-certificate-errors"])
driver=webdriver.Chrome(executable_path="C:\Program Files (x86)\Google\Chrome\Application\chromedriver.exe",chrome_options=options) #调用chrome浏览器
#print dir(driver)
driver.get('https://sanya.nuomi.com/326')
#点击按钮
#driver.find_element_by_class_name("next-btn").click()
#
page = driver.page_source
# print(page)
# print type(page)
#
soup = BeautifulSoup(page,'html.parser',from_encoding="utf-8")
# print soup.prettify()
#
div_list=soup.find_all("div", class_="contentbox")
shopUrl=""
shopName=""
index=1001
for con in div_list:
index+=1
shopUrl=("https:"+con.a.get("href")).encode('utf-8')#[color=red]转码,插入mysql后不会乱码[/color]
shopName=(con.h4.get_text()).encode('utf-8')
# shopUrl.encode('utf-8')
# shopName.encode('utf-8')
print shopUrl,shopName
print 'insert into k_bdnm_shopinfo values(%d,%s,%s)'%(index,shopUrl,shopName)
try:
cur.execute("insert into k_bdnm_shopinfo values(%d,'%s','%s')"%(index,shopUrl,shopName))
except MySQLdb.Error, e:
print "Mysql Error %d: %s" % (e.args[0], e.args[1])

driver.quit()
closeDBConnandCur(cur,mysqlConn)#关闭游标和数据库连接

'''
数据表信息
'''
CREATE TABLE `k_bdnm_shopinfo` (
`shop_id` int(11) NOT NULL auto_increment,
`shop_url` varchar(300) NOT NULL,
`shop_name` varchar(100) NOT NULL,
PRIMARY KEY (`shop_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

sort浅忆

觉得有用,大大们可以打赏1毛毛

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值