Python爬虫爬取、解析数据操作示例
本文实例讲述了Python爬虫爬取、解析数据操作。分享给大家供大家参考,具体如下:
爬虫当当网http://search.dangdang.com/?key=python&act=input&page_index=1
- 获取书籍相关信息
- 面向对象思想
- 利用不同解析方式和存储方式
引用相关库
importrequests importre importcsv importpymysql frombs4importBeautifulSoup fromlxmlimportetree importlxml fromlxmlimporthtml
类代码实现部分
classDDSpider(object):
#对象属性参数关键字页数
def__init__(self,key='python',page=1):
self.url='http://search.dangdang.com/?key='+key+'&act=input&page_index={}'
self.page=page
self.headers={'User-Agent':'Mozilla/5.0(WindowsNT10.0;WOW64)AppleWebKit/537.36(KHTML,likeGecko)Chrome/53.0.2785.116Safari/537.36'}
#私有对象方法
def__my_url(self):
my_url=[]
ifself.page<1:
my_page=2
else:
my_page=self.page+1
#循环遍历每一页
foriinrange(1,my_page):
my_url.append(self.url.format(i))
returnmy_url
#私有对象方法请求数据
def__my_request(self,url,parser_type):
#循环遍历每一页
response=requests.get(url=url,headers=self.headers)
ifresponse.status_code==200:
returnself.__my_parser(response.text,parser_type)
else:
returnNone
#私有对象方法解析数据1利用正则2bs43xpath
def__my_parser(self,html,my_type=1):
ifmy_type==1:
pattern=re.compile('(.*?).*?(.*?).*?.*?',re.S)
result=re.findall(pattern,html)
elifmy_type==2:
soup=BeautifulSoup(html,'lxml')
result=[]
title_url=soup.find_all('a',attrs={'name':'itemlist-title'})
foriinrange(0,len(title_url)):
title=soup.find_all('a',attrs={'name':'itemlist-title'})[i].attrs['title']
url=soup.find_all('a',attrs={'name':'itemlist-title'})[i].attrs['href']
price=soup.find_all('span',attrs={'class':'search_now_price'})[i].get_text()
author=soup.find_all('a',attrs={'name':'itemlist-author'})[i].attrs['title']
desc=soup.find_all('p',attrs={'class':'detail'})[i].get_text()
my_tuple=(title,url,desc,price,author)
result.append(my_tuple)
else:
html=etree.HTML(html)
li_all=html.xpath('//div[@id="search_nature_rg"]/ul/li')
result=[]
foriinrange(len(li_all)):
title=html.xpath('//div[@id="search_nature_rg"]/ul/li[{}]/p[@class="name"]/a/@title'.format(i+1))
url=html.xpath('//div[@id="search_nature_rg"]/ul/li[{}]/p[@class="name"]/a/@href'.format(i+1))
price=html.xpath('//div[@id="search_nature_rg"]/ul/li[{}]//span[@class="search_now_price"]/text()'.format(i+1))
author_num=html.xpath('//div[@id="search_nature_rg"]/ul/li[{}]/p[@class="search_book_author"]/span[1]/a'.format(i+1))
iflen(author_num)!=0:
#有作者a标签
author=html.xpath('//div[@id="search_nature_rg"]/ul/li[{}]/p[@class="search_book_author"]/span[1]/a[1]/@title'.format(i+1))
else:
#没有作者a标签
author=html.xpath('//div[@id="search_nature_rg"]/ul/li[{}]/p[@class="search_book_author"]/span[1]/text()'.format(i+1))
desc=html.xpath('//div[@id="search_nature_rg"]/ul/li[{}]/p[@class="detail"]/text()'.format(i+1))
my_tuple=("".join(title),"".join(url),"".join(desc),"".join(price),"".join(author))
result.append(my_tuple)
returnresult
#私有对象方法存储数据1txt2csv3mysql
def__my_save(self,data,save_type=1):
#循环遍历
forvalueindata:
ifsave_type==1:
withopen('ddw.txt','a+',encoding="utf-8")asf:
f.write('【名称】:{}【作者】:{}【价格】:{}【简介】:{}【链接】:{}'.format(value[0],value[4],value[3],value[2],value[1]))
elifsave_type==2:
withopen('ddw.csv','a+',newline='',encoding='utf-8-sig')asf:
writer=csv.writer(f)
#转化为列表存储
writer.writerow(list(value))
else:
conn=pymysql.connect(host='127.0.0.1',user='root',passwd='',db='',port=3306,charset='utf8')
cursor=conn.cursor()
sql=''
cursor.execute(sql)
conn.commit()
cursor.close()
conn.close()
#公有对象方法执行所有爬虫操作
defmy_run(self,parser_type=1,save_type=1):
my_url=self.__my_url()
forvalueinmy_url:
result=self.__my_request(value,parser_type)
self.__my_save(result,save_type)
调用爬虫类实现数据获取
if__name__=='__main__':
#实例化创建对象
dd=DDSpider('python',0)
#参数解析方式my_run(parser_type,save_type)
#parser_type1利用正则2bs43xpath
#存储方式save_type1txt2csv3mysql
dd.my_run(2,1)
==总结一下:==
1.总体感觉正则表达式更简便一些,代码也会更简便,但是正则部分相对复杂和困难
2.bs4和xpath需要对html代码有一定了解,取每条数据多个值时相对较繁琐
更多关于Python相关内容可查看本站专题:《PythonSocket编程技巧总结》、《Python正则表达式用法总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总》
希望本文所述对大家Python程序设计有所帮助。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。