步驟
- 將目標網站下的頁面抓取下來
- 將抓取下來的數據根據一定規則進行提取
具體流程
- 將目標網站下的頁面抓取下來
1. 倒庫
import requests
2.頭信息(有時候可不寫)
headers = {
#請求身份/默認為User-Agent:python
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.87 Safari/537.36',
'Referer': 'https://movie.douban.com/'
}
3.url
url = 'https://movie.douban.com/cinema/nowplaying/zhengzhou/'

4.返回響應
response = requests.get(url,headers=headers) #響應 #print(response.text) text = response.text
response.text:返回的是一個經過解碼后的字符串,是str(unicode)類型
response.concent:返回的是一個原生的字符串,就是從網頁上抓取下來的,沒有經過解碼的字符串,是bytes類型
2.將抓取下來的數據根據一定規則進行提取
1.將爬取下來是數據用lxml進行解析
from lxml import etree html = etree.HTML(text)
2.獲取ul、li下的 'title'、'score'、'poster'
先看看框架
ul (class='list')
li ······
ul
li
a ······
ul = html.xpath("//ul[@class='lists']")[0]
#print(etree.tostring(ul,encoding='utf-8').decode('utf-8'))
lis = ul.xpath('./li')
for li in lis:
#print(etree.tostring(li,encoding='utf-8').decode('utf-8'))
title = li.xpath('@data-title')[0]
#print(title)
score = li.xpath('@data-score')[0]
# print(score)
poster = li.xpath('.//img/@src')[0]
# print(poster)
[0] 只獲取第一個內容
// 獲取網頁當中所有的元素
./ 在當前標簽下獲取
.// 在當前標簽下下獲取
xpath返回的是列表的形式 [''],[0]就可以只拿內容
3.儲存信息
1.下載
request.urlretrieve(poster, 'D:/A/' + score + title + '.jpg')
下載到D盤下A目錄中,文件名為 評分+影名.jpg
2.顯示進度條
fns_num = 1
num = len(lis)
for li in lis:
···
print("\r完成進度: {:.2f}%".format(fns_num * 100 / num), end="")
fns_num += 1
完整代碼
#coding=UTF-8
import requests
from lxml import etree
from urllib import request
headers = {
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.87 Safari/537.36',
'Referer': 'https://movie.douban.com/'
}
url = 'https://movie.douban.com/cinema/nowplaying/zhengzhou/'
response = requests.get(url,headers=headers)
# print(response.text)
text = response.text
html = etree.HTML(text)
ul = html.xpath("//ul[@class='lists']")[0]
# print(etree.tostring(ul,encoding='utf-8').decode('utf-8'))
lis = ul.xpath("./li")
# movies = []
fns_num = 1
num = len(lis)
for li in lis:
# print(etree.tostring(li,encoding='utf-8').decode('utf-8'))
title = li.xpath('@data-title')[0]
# print(title)
score = li.xpath('@data-score')[0]
# print(score)
poster = li.xpath('.//img/@src')[0]
# print(poster)
request.urlretrieve(poster, 'D:/A/' + score + title + '.jpg')
print("\r完成進度: {:.2f}%".format(fns_num * 100 / num), end="")
fns_num += 1
