问题解决
这是我昨天发的简书python爬虫之豆瓣音乐top250大牛们解决了一大部分的问题
1 MySQL报错问题
字段长度设置太小,说着也很奇怪,我用的vachar(20)都说小了,哎,后面建表干脆用text型,数据量不大还行。
2 爬不到数据的问题
我只能说是完美答案,我在这就不解释了,这个简友是it互联网的编辑,平时也会写很多Python爬虫的文章,大家可以去看看,今天的Xpath文章就是一个简友还有这个向右奔跑的帮助下完成的,在此谢谢他们,另一个等会再提,哈哈。
3 代码累赘问题
这种会节省一定的代码量,今天的代码有用到哦!
用xpath方法爬取豆瓣图书top250
xpath方法去看看向右奔跑的文章就好啦,讲的很好,我就不在这班门弄斧啦,还推荐一个我的好友:好友博客,今天的大部分代码是他指导完成的,也是他指导我学的Mysql,大家一起学习很开心,来看代码:
from lxml import etree
import requests
import time
import pymysql
conn = pymysql.connect(host='localhost', user='root', passwd='123456', db='test', port=3306, charset='utf8')
cursor = conn.cursor()
urls = ['https://book.douban.com/top250?start={}'.format(str(i)) for i in range(0,250,25)]
headers = {
'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36'
}
for url in urls:
html = requests.get(url,headers=headers)
selector = etree.HTML(html.text)
infos = selector.xpath('//tr[@class="item"]')
for info in infos:
name = info.xpath('td/div/a/@title')[0]
url = info.xpath('td/div/a/@href')[0]
book_infos = info.xpath('td/p/text()')[0]
author = book_infos.split('/')[0]
publisher = book_infos.split('/')[-3]
date = book_infos.split('/')[-2]
price = book_infos.split('/')[-1]
rate = info.xpath('td/div/span[2]/text()')[0]
comments = info.xpath('td/p/span/text()')
comment = comments[0] if len(comments) != 0 else "空"
cursor.execute("use test")
cursor.execute("insert into doubanbook (name,url,author,publisher,date,price,rate,comment) values(%s,%s,%s,%s,%s,%s,%s,%s)",
(str(name),str(url),str(author),str(publisher),str(date),str(price),str(rate),str(comment)))
time.sleep(2)
conn.commit()
xpath比beatifulsoup解析难一点,关键是找循环点,下面是我建表的mysql代码:
CREATE TABLE doubanbook (
name TEXT,
url TEXT,
author TEXT,
publisher TEXT,
dateTEXT,
price TEXT,
rate TEXT,
comment TEXT
)ENGINE INNODB DEFAULT CHARSET=utf8 ;
分析
SELECT * FROM doubanbook;
下面是出版量前五的出版社
SELECT publisher,COUNT(*) AS numbers FROM doubanbook GROUP BY publisher ORDER BY numbers DESC LIMIT 0,5;
评分前十的图书,想看书的给你们推荐一波
SELECT NAME,author,publisher,rate,COMMENT FROM doubanbook ORDER BY rate DESC LIMIT 0,10;
总结
今天主要是学习了xpath爬取数据的方法,其次是练习了一下mysql的查询语法,查询的数据可以进行可视化分析,我今天就不做了,春节快乐。
网友评论