爬虫学习笔记--用selenium 爬数据到Mysql

# -*- coding:utf-8 -*-
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import MySQLdb;
import sys
import time
reload(sys)
sys.setdefaultencoding('utf-8')

con = MySQLdb.connect(host='localhost',user='root',passwd='xxxx',db='xiehui',charset="utf8")
cur = con.cursor()

fp = webdriver.FirefoxProfile()
fp.set_preference("permissions.default.stylesheet",2)
fp.set_preference("permissions.default.image",2)
app = webdriver.Firefox(firefox_profile=fp)
app.get("http://www.baidu.com")

search_handle = app.current_window_handle
print str(search_handle) + "------"

search = app.find_element_by_xpath(".//*[@id='kw']")
search.clear()
search.send_keys("songganaiyi")
searbtn = app.find_element_by_xpath(".//*[@id='su']").send_keys(Keys.ENTER)

time.sleep(3)
xiehuicitiao = app.find_element_by_xpath(".//*[@id='1']/h3/a")
xiehuicitiao.click()
time.sleep(3)
all_handle = app.window_handles
print str(all_handle)+"-----------"
for handle in all_handle:
    if handle != search_handle:
        app.switch_to.window(handle)
        # print app.title
        # print app.current_url
        contents = app.find_elements_by_css_selector('div.para')
        for para in contents:
            print str(para.text).strip()
            cur.execute('insert into paras (para) values("%s");' % (str(para.text).strip()))
        cur.close()
        con.commit()
    elif handle == search_handle:
        print "error-----"

app.quit()

这里我用selenium模拟浏览器 爬取百度词条里的内容 保存到Mysql

有几个说明的地方 

1.中文编码 在Pycharm里有时会乱码 加上

# -*- coding:utf-8 -*-

import sys
reload(sys)
sys.setdefaultencoding('utf-8')

2.python 安装 mysql的库 会有错 具体请看 这篇文章下载安装

 http://www.mamicode.com/info-detail-1222077.html

3.mysql 在插入过程中 我遇到了 字符串有 单分号的 情况 这时会插入失败 

因此 插入语句 这里请用双引号

values("%s")


  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值