# -*- 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 -*-
和
importsys
reload(sys)
sys.setdefaultencoding('utf-8')
2.python 安装 mysql的库 会有错 具体请看 这篇文章下载安装
http://www.mamicode.com/info-detail-1222077.html
3.mysql 在插入过程中 我遇到了 字符串有 单分号的 情况 这时会插入失败
因此 插入语句 这里请用双引号values("%s")