我最近在看崔庆才老师的《python3 网络爬虫开发实战》觉得挺不错的,上面还有一个 用正则表达式爬取猫眼电影的电影排行榜 我练了一下,感觉不会很难,后来学到了xpath,就想用xpath去爬取,结果发现比正则表达式简单多了
下面讲一下基本原理,
- 先用 respone =requests.get(url,headers=headers) 获取html文件
这里要注意的是,猫眼电影加了反爬虫(可能是拿它练手的人太多了吧),所以最好加上User-Agent - 利用xpath 提取上面得到的html文件,根据
<p class="name">
这些标签获取电影名、主演、上映时间等
上代码
# -*- coding: utf-8 -*-
# @Time : 2018/9/24 12:04
# @Author : Tangweeiyang
# @File : Maoyang_spider.py
import requests
from lxml import etree
index=1
#获取猫眼HTML
def get_one_page(url):
headers={
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:54.0) Gecko/20100101 Firefox/54.0',
}
respone =requests.get(url,headers=headers) # 一定要加上header否则,无法爬取猫眼的网页
if respone.status_code==200:
return respone.text
else:
return None
# 获取数据
def parse_one_page(text):
html=etree.HTML(text)
movies_name=html.xpath('//p[@class="name"]//text()')
movies_star=html.xpath('//p[@class="star"]//text()')
movies_time = html.xpath('//p[@class="releasetime"]//text()')
global index
with open('Maoyan.txt','a+',encoding='utf-8') as file: #编码格式一定要写成'utf-8' 否则后面会乱码
for i in range(0,10):
file.write('排名第%s'%index+'电影:\t'+movies_name[i].strip()+'\t'+movies_star[i].strip()+'\t'+movies_time[i].strip()+'\n')
print(movies_name[i].strip(),movies_star[i].strip(),movies_time[i].strip())
index+=1
if __name__ == '__main__':
with open('Maoyan.txt', 'w', encoding='utf-8') as file:
file.write('猫眼电影排名前100电影名单如下\n')
url_start='https://maoyan.com/board/4?offset='
for i in range(0,100,10):
url=url_start+str(i) #有个小陷阱,不能写成 url_start=url_start+str(i)
text=get_one_page(url)
parse_one_page(text)