使用Requests和Xpath简单爬取并输出豆瓣电影(济南)代码。

import requests #导入请求库
from lxml import etree #导入xpath
#确定抓取目标网页
url ="https://movie.douban.com/cinema/nowplaying/jinan/"
#设置请求头
headers = {
"User-Agent":"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 SE 2.X MetaSr 1.0"
}
#发送get请求
response = requests.get(url=url,headers=headers)
#获取解析结果
text = response.text
#对数据进行解析:
#定义一个空列表用来存储最后的数据
video_infomation = []
#将返回的结果变成属性结构便于xpath语法提取
html = etree.HTML(text)
#查找class=lists的ul元素并将列表值提取出来:
#查看属性结构的HTML输出网页样式,用到tostring方法。
# result = etree.tostring(html).decode("utf-8")
# print(result)
ul = html.xpath('//ul[@class="lists"]')[0]#对的 可以输出 外围引号用英文单引号 内部引号用英文双引号
lis = ul.xpath("./li")
#遍历列表
for li in lis:
data_title = li.xpath("@data-title")[0]
data_score = li.xpath("@data-score")[0]
data_region=li.xpath("@data-region")[0]
data_actors=li.xpath("@data-actors")[0]
img = li.xpath(".//img/@src")[0]
#将获取到的数据存入字典
video_info = {
'电影名':data_title,
'电影评分':data_score,
'电影来源':data_region,
'电影主演':data_actors,
'电影海报':img
}
#将字典存在列表中
video_infomation.append(video_info)
#输出这个列表
for item in video_infomation:
print(item)
 

以上代码,亲测可以运行输出。2019-03-10——20:15:58。但是有一个疑问,请见下面箭头所示,为何网页源代码中后缀为webp,输出后为jpg格式?是自动导出变更图片的另一种形式吗?

猜你喜欢

转载自www.cnblogs.com/seajay/p/10507824.html