学习Python selenium自动化网页抓取器
直接入正题---Pythonselenium自动控制浏览器对网页的数据进行抓取,其中包含按钮点击、跳转页面、搜索框的输入、页面的价值数据存储、mongodb自动id标识等等等。
1、首先介绍一下Pythonselenium---自动化测试工具,用来控制浏览器来对网页的操作,在爬虫中与BeautifulSoup结合那就是天衣无缝,除去国外的一些变态的验证网页,对于图片验证码我有自己写的破解图片验证码的源代码,成功率在85%。
详情请咨询QQ群--607021567(这不算广告,群里有好多Python的资源分享,还有大数据的一些知识【hadoop】)
2、beautifulsoup就不需要详细的介绍了,直接上网址::https://www.crummy.com/software/BeautifulSoup/bs4/doc/(BeautifulSoup的官方文档)
3、关于mongodb的自动id的生成。mongodb中所有的存储数据都是有固定的id的,但是mongodb的id对于人类来讲是复杂的,对于机器来讲是小菜一碟的,所以在存入数据的同时,我习惯用新id来对每一条数据的负责!
在Python中使用mongodb的话需要引进模块frompymongoimportMongoClient,ASCENDING,DESCENDING,该模块就是你的责任!
接下来开始讲程序,直接上实例(一步一步来):
引入模块:
fromseleniumimportwebdriver frombs4importBeautifulSoup importrequests frompymongoimportMongoClient,ASCENDING,DESCENDING importtime importre
其中的每一个模块都会说已经解释过了,其中的re、requests都是之前就有提过的,他们都是核心缺一不可!
首先,我举一个小例子,淘宝的自动模拟搜索功能(源码):
先说一下selenium的定位方法
find_element_by_id find_element_by_name find_element_by_xpath find_element_by_link_text find_element_by_partial_link_text find_element_by_tag_name find_element_by_class_name find_element_by_css_selector
源码:
fromseleniumimportwebdriver frombs4importBeautifulSoup importrequests frompymongoimportMongoClient,ASCENDING,DESCENDING importtime importre defTaoBao(): try: Taobaourl='https://www.taobao.com/' driver=webdriver.Chrome() driver.get(Taobaourl) time.sleep(5)#通常这里需要停顿,不然你的程序很有可能被检测到是Spider text='StrongMan'#输入的内容 driver.find_element_by_xpath('//input[@class="search-combobox-input"]').send_keys(text).click() driver.find_element_by_xpath('//button[@class="btn-searchtb-bg"]').click() driver.quit() exceptException,e: printe if__name__=='__main__': TaoBao()
效果的实现,你们可以直接复制后直接运行!我只用了xpath的这个方法,因为它最实在!橙色字体(如果我没有色盲的话),就是网页中定位的元素,可以找到的!
接下来就是与BeautifulSoup的结合了,但是我们看到的只是打开了网页,并没有源码,那么就需要“变量名.page_source”这个方法,他会实现你的梦想,你懂得?
ht=driver.page_source #printht你可以Print出啦看看 soup=BeautifulSoup(ht,'html.parser')
下面就是BeautifulSoup的一些语法操作了,对于数据的结构还有采集,在上一篇里面有详细的抓取操作!!!
算了!说一个最简单的定位抓取:
soup=BeautifulSoup(ht,'html.parser') a=soup.find('table',id="ctl00_ContentMain_SearchResultsGrid_grid") ifa:#必须加判断,不然访问的网页或许没有这一元素,程序就会都停止!
class的标签必须是class_,一定要记住!
哈哈哈!mongodb了昂,细节细节,首先需要用到模块----frompymongoimportMongoClient,ASCENDING,DESCENDING
因为在python,mongodb的语法仍然实用,所以需要定义一个库,并且是全局性的,还有链接你计算机的一个全局变量。
if__name__=='__main__': globaldb#全局变量 globaltable#全局数据库 table='mouser_product' mconn=MongoClient("mongodb://localhost")#地址 db=mconn.test db.authenticate('test','test')#用户名和密码 Taobao()
定义这些后,需要我们的新id来对数据的跟踪加定义:
db.sn.find_and_modify({"_id":table},update={"$inc":{'currentIdValue':1}},upsert=True) dic=db.ids.find({"_id":table}).limit(1) returndic[0].get("currentIdValue")
这个方法是通用的,所以只要记住其中的mongodb的语法就可以了!因为这里是有返回值的,所以这个是个方法体,这里不需要太过于纠结是怎么实现的,理解就好,中心还是在存数据的过程中
count=db[table].find({'数据':数据}).count()#是检索数据库中的数据 ifcount<=0:#判断是否有 ids=getNewsn()#ids就是我们新定义的id,这里的id是1开始的增长型id db[table].insert({"ids":ids,"数据":数据})
这样我们的数据就直接存入到mongodb的数据库中了,这里解释一下为什么在大数据中这么喜欢mongodb,因为它小巧,速度佳!
最后来一个实例源码:
fromseleniumimportwebdriver frombs4importBeautifulSoup importrequests frompymongoimportMongoClient,ASCENDING,DESCENDING importtime importre defparser(): try: f=open('sitemap.txt','r') foriinf.readlines(): sorturl=i.strip() driver=webdriver.Firefox() driver.get(sorturl) time.sleep(50) ht=driver.page_source #pageurl(ht) soup=BeautifulSoup(ht,'html.parser') a=soup.find('a',class_="first-last") ifa: pagenum=int(a.get_text().strip()) printpagenum foriinxrange(1,pagenum): element=driver.find_element_by_xpath('//a[@id="ctl00_ContentMain_PagerTop_%s"]'%i) element.click() html=element.page_source pageurl(html) time.sleep(50) driver.quit() exceptException,e: printe defpageurl(ht): try: soup=BeautifulSoup(ht,'html.parser') a=soup.find('table',id="ctl00_ContentMain_SearchResultsGrid_grid") ifa: tr=a.find_all('tr',class_="SearchResultsRowOdd") iftr: foriintr: td=i.find_all('td') iftd: url=td[2].find('a') ifurl: producturl='网址'+url['href'] printproducturl count=db[table].find({"url":producturl}).count() ifcount<=0: sn=getNewsn() db[table].insert({"sn":sn,"url":producturl}) printstr(sn)+'insertedsuccessfully' time.sleep(3) else: print'existsurl' tr1=a.find_all('tr',class_="SearchResultsRowEven") iftr1: foriintr1: td=i.find_all('td') iftd: url=td[2].find('a') ifurl: producturl='网址'+url['href'] printproducturl count=db[table].find({"url":producturl}).count() ifcount<=0: sn=getNewsn() db[table].insert({"sn":sn,"url":producturl}) printstr(sn)+'insertedsuccessfully' time.sleep(3) else: print'existsurl' #time.sleep(5) exceptException,e: printe defgetNewsn(): db.sn.find_and_modify({"_id":table},update={"$inc"{'currentIdValue':1}},upsert=True) dic=db.sn.find({"_id":table}).limit(1) returndic[0].get("currentIdValue") if__name__=='__main__': globaldb globaltable table='mous_product' mconn=MongoClient("mongodb://localhost") db=mconn.test db.authenticate('test','test') parser()
这一串代码是破解一个老外的无聊验证码界面结缘的,我真的对他很无语了!破解方法还是实践中!这是完整的源码,无删改的哦!纯手工!