總的:
1.from lxml import etree
2.對(duì)html文本使用 etree.HTML(html)解析,得到Element對(duì)象
3.對(duì)Element對(duì)象使用xpath篩選(中間會(huì)穿插使用正則表達(dá)式),返回一個(gè)列表
4.本文為實(shí)戰(zhàn)爬取豆瓣電影top250的信息,并將數(shù)據(jù)存入mysql中
5.用Navicat進(jìn)行數(shù)據(jù)的可視化
實(shí)戰(zhàn):
導(dǎo)入要用到的庫(kù)
import requests
from lxml import etree
import re
import pymysql
import time定義函數(shù)用來(lái)解析html
#建立數(shù)據(jù)庫(kù)連接,(數(shù)據(jù)庫(kù)中原先就應(yīng)該有一個(gè)database,如果沒(méi)有要先創(chuàng)建一個(gè)database,我這里創(chuàng)建的叫scraping)
conn = pymysql.connect(host='127.0.0.1', user='root', passwd='yourpasswd', db='scraping', port=3306, charset='utf8')
cursor = conn.cursor()
#頭文件
headers = {
'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36'
}
#定義的獲取電影url的函數(shù)
def get_movie_url(url):
html = requests.get(url,headers=headers)
#解析html
selector = etree.HTML(html.text)
#利用xpath獲取電影url
movie_hrefs = selector.xpath('//div[@class="hd"]/a/@href')
for movie_href in movie_hrefs:
get_movie_info(movie_href)

獲取的url
- 定義子函數(shù)用來(lái)解析每一部電影(每個(gè)url)的元素屬性
def get_movie_info(url):
html = requests.get(url,headers=headers)
selector = etree.HTML(html.text)
try:
name = selector.xpath('//*[@id="content"]/h1/span[1]/text()')[0].strip()
director = selector.xpath('//*[@id="info"]/span[1]/span[2]/a/text()')[0].strip()
actors = selector.xpath('//*[@id="info"]/span[3]/span[2]')[0]
actor = actors.xpath('string(.)')
style = re.findall('<span property="v:genre">(.*?)</span>',html.text,re.S)[0].strip()
country = re.findall('<span class="pl">制片國(guó)家/地區(qū):</span> (.*?)<br/>',html.text,re.S)[0].strip()
release_time = re.findall('上映日期:</span>.*?>(.*?)</span>',html.text,re.S)[0].strip()
time = re.findall('片長(zhǎng):</span>.*?>(.*?)</span>',html.text,re.S)[0].strip()
score = selector.xpath('//*[@id="interest_sectl"]/div[1]/div[2]/strong/text()')[0].strip()
#在數(shù)據(jù)庫(kù)中建立表格叫doubanmovie,表中包括以上屬性
cursor.execute(
"insert into doubanmovie (name,director,actor,style,country,release_time,time,score) values(%s,%s,%s,%s,%s,%s,%s,%s)",
(str(name), str(director), str(actor), str(style), str(country), str(release_time), str(time), str(score)))
except IndexError:
pass
- 實(shí)現(xiàn)
if __name__ == '__main__':
#獲取電影榜top250,網(wǎng)站把排名分為10頁(yè),每頁(yè)25部電影,所以用以下形式構(gòu)造url
urls = ['https://movie.douban.com/top250?start={}'.format(str(i)) for i in range(0, 250, 25)]
for url in urls:
get_movie_url(url)
time.sleep(2)
#把數(shù)據(jù)寫(xiě)入數(shù)據(jù)庫(kù)的表中
conn.commit()
-
效果
數(shù)據(jù)列表
專(zhuān)為簡(jiǎn)化數(shù)據(jù)庫(kù)的管理及降低系統(tǒng)管理成本而設(shè)。它的設(shè)計(jì)符合數(shù)據(jù)庫(kù)管理員、開(kāi)發(fā)人員及中小企業(yè)的需要。Navicat 是以直覺(jué)化的圖形用戶(hù)界面而建的,讓你可以以安全并且簡(jiǎn)單的方式創(chuàng)建、組織、訪問(wèn)并共用信息。
Navicat目前還是一款收費(fèi)軟件,但是可以在網(wǎng)絡(luò)上尋找一些破解版本,也可以找筆者要,筆者很樂(lè)意和大家分享學(xué)習(xí)經(jīng)驗(yàn),也希望大家多多指導(dǎo)筆者,共同進(jìn)步!筆者微信wuzhenpingcc。

