? ? ? 本文將介紹利用Requests、Lxml第三方庫及逆向工程方法,爬去簡書用戶文章信息,并通過pymysql庫將爬取數(shù)據(jù)放到mysql數(shù)據(jù)庫中。??
? ? ?需要的工具:python3、mysql
? ? ?需要安裝的包:Requets、Lxml、pymsql? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?
? ? ? ?本文以爬取簡書用戶三步一叩首的文章信息為例,爬去數(shù)據(jù)包括:文章標題、閱讀量、評論數(shù)、點贊量? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?

? ? 在寫爬蟲之前,先在數(shù)據(jù)庫database中新建jianshu表來存放爬取的數(shù)據(jù),代碼如下:? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?

本文使用Xpath來解析網(wǎng)頁,具體代碼如下:

import requests
from lxml import etree
import pymysql
conn = pymysql.connect(host='localhost',user='root',passwd='200709',db='database',port=3306,charset='utf8')
cursor = conn.cursor()
urls = ['http://www.itdecent.cn/u/57521b4790dc?order_by=shared_at&page={}'.format(str(i)) for i in range(1,17)]
headers = {
? ? 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36'
? ? }
for url in urls:
? ? html = requests.get(url,headers=headers)
? ? selector = etree.HTML(html.text)
? ? infos = selector.xpath('//ul[@class="note-list"]/li')
? ? for info in infos:
? ? ? ? title = info.xpath('div/a/text()')[0]
? ? ? ? total_read = info.xpath('div/div/a[1]/text()')[1].strip()
? ? ? ? words = info.xpath('div/div/a[2]/text()')[1].strip()
? ? ? ? liked = info.xpath('div/div/span[1]/text()')[0].strip()
? ? ? ? cursor.execute("insert into jianshu(title,total_read,words,liked) values(%s,%s,%s,%s)",
? ? ? ? ? ? ? ? ? ? ? (str(title),str(total_read),str(words),str(liked)))
? ? ? ? conn.commit()
運行代碼過后,打開mysql,發(fā)現(xiàn)數(shù)據(jù)已經(jīng)保存到jianshu表中。
