Python3简单爬虫:爬取猫眼评分top100电影
Python3:用xpath库爬取猫眼评分top100电影
在看《Python3 网络爬虫开发实战中》一书学习时,书中第三章例子用re正则匹配来爬取电影的所需数据,虽然爬取速度快,效率好,但是可能在写匹配规则时一点疏忽就会导致匹配失败提取不到所需数据,因此本次用xpath来提取内容!
-
本次所需了解的库:
xpath库语法:http://www.w3school.com.cn/xpath/xpath_syntax.asp
tip:在不熟悉所需库的语法时,尽量先去了解库的基本语法哦!
用re爬取代码如下:
import json
import requests
from requests.exceptions import RequestException
import re
import time
#first:抓取页面
def get_one_page(url):
try:
headers = {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.162 Safari/537.36'
}
response = requests.get(url, headers=headers)
if response.status_code == 200:
return response.text
return None
except RequestException:
return None
#second:解析获取到的每一页源码,提取所需内容
def parse_one_page(html):
pattern = re.compile('<dd>.*?board-index.*?>(\d+)</i>.*?data-src="(.*?)".*?name"><a'
+ '.*?>(.*?)</a>.*?star">(.*?)</p>.*?releasetime">(.*?)</p>'
+ '.*?integer">(.*?)</i>.*?fraction">(.*?)</i>.*?</dd>', re.S)
items = re.findall(pattern, html) #正则提取
for item in items:
yield {
'index': item[0],
'image': item[1],
'title': item[2],
'actor': item[3].strip()[3:],
'time': item[4].strip()[5:],
'score': item[5] + item[6]
}
#third:将数据内容保存到TXT文档
def write_to_file(content):
with open('maoyanFile_top100.txt', 'a', encoding='utf-8') as f:
f.write(json.dumps(content, ensure_ascii=False) + '\n')
def main(offset):
url = 'http://maoyan.com/board/4?offset=' + str(offset)
html = get_one_page(url)
for item in parse_one_page(html):
print(item)
write_to_file(item)
if __name__ == '__main__':
for i in range(10):
main(offset=i * 10) #翻页
time.sleep(1) #设置休眠时间,防止IP被封
上面代码中用re提取的匹配规则较为复杂,有点小难度。
不理解的可以了解一下re的基本规则和匹配函数:
https://blog.****.net/qq_42908549/article/details/86653767
-
使用xpath 爬取
第一步:用xpath提取内容时,第一步先用谷歌仔细查看源代码,再仔细查看其中一个电影信息的源代码(如图所示):
发现每个电影对应的源代码是一个dd节点,所以我们用xpath来提取里面的一些我们需要的电影信息:
(1)找到排名所在的节点:在 i 节点上
(2)找到照片对应节点:节点a下第二个img那里
(3)找到电影名字:在第三层 div 下 p 节点下的a节点下
演员、上映时间以及具体评分的提取也是按照这样的方式仔细寻找!
提取代码如下:
#second:解析获取到的每一页源码,提取所需内容
def parse_one_page(html):
selector=etree.HTML(html.text)
infos = selector.xpath('//dd')
for info in infos:
index=info.xpath('i/text()')[0]
image=info.xpath('a/img[2]/@data-src')
title=info.xpath('div/div/div/p[@class="name"]/a/text()')[0]
actor=info.xpath('div/div/div/p[@class="star"]/text()')[0].strip('\n').strip(' ')
time=info.xpath('div/div/div/p[@class="releasetime"]/text()')[0]
score=info.xpath('div/div/div/p[@class="score"]/i[@class="integer"]/text()')[0]+info.xpath(
'div/div/div/p[@class="score"]/i[@class="fraction"]/text()'
)[0]
yield {
'index':index,
'image':image,
'title':title,
'actor':actor,
'time' :time,
'score':score
}
这样就可以提取到所有我们要的电影信息啦!
第二步:将所有提取到的信息保存到文档
前面生成的数据比较杂乱,所以使用 **yield** 方法提取结果生成字典,这里通过**json**库的**dumps()**方法实现字典的序列化(具体代码看后面的整体代码)
基本过程就是这样啦,个人觉得xpath库相对于正则匹配会比较容易一些,对于和我一样的初学者上手较快,很适合小白入门。下面附上完整代码:
import json
import requests
from requests.exceptions import RequestException
from lxml import etree
import time
#first:抓取页面
def get_one_page(url):
try:
headers = {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.162 Safari/537.36'
}
response = requests.get(url, headers=headers)
if response.status_code == 200:
return response
return None
except RequestException:
return None
#second:解析获取到的每一页源码,提取所需内容
def parse_one_page(html):
selector=etree.HTML(html.text)
infos = selector.xpath('//dd')
for info in infos:
index=info.xpath('i/text()')[0]
image=info.xpath('a/img[2]/@data-src')
title=info.xpath('div/div/div/p[@class="name"]/a/text()')[0]
actor=info.xpath('div/div/div/p[@class="star"]/text()')[0].strip('\n').strip(' ')
time=info.xpath('div/div/div/p[@class="releasetime"]/text()')[0]
score=info.xpath('div/div/div/p[@class="score"]/i[@class="integer"]/text()')[0]+info.xpath(
'div/div/div/p[@class="score"]/i[@class="fraction"]/text()'
)[0]
yield {
'index':index,
'image':image,
'title':title,
'actor':actor,
'time' :time,
'score':score
}
#third:将数据内容保存到TXT文档
def write_to_file(content):
with open('maoyanFile_100.txt', 'a', encoding='utf-8') as f:
f.write(json.dumps(content, ensure_ascii=False) + '\n')
if __name__ == '__main__':
for i in range(0,10):
url = 'http://maoyan.com/board/4?offset=' + str(i*10)
html=get_one_page(url)
parse_one_page(html)
for item in parse_one_page(html):
print(item)
write_to_file(item)
time.sleep(1) #设置休眠时间,防止IP被封
-
最后爬取成功截图: