python爬取数据(豆瓣上TOP250的电影信息)初学者必看!!!
日期: 2018-07-18 分类: 个人收藏 401次阅读
python爬取豆瓣上TOP250电影
初学python爬虫。我这里用的 lxml提取xpath的方式来爬取数据 lxml爬取的速度会比bs4快,所以这里我选用的lxml
话不多上,赶紧上教程。
爬取的思路:
1.获取网页解析(有些网页需要代理)
2.解析完成之后,分析我们需要提取的数据的格式 这里用xpath的方法
3.爬取之后存储,存储数据
我们这次爬取的地址是: https://movie.douban.com/top250
分析下一下网址:
https://movie.douban.com/top250?start=0
https://movie.douban.com/top250?start=50
https://movie.douban.com/top250?start=250
后面的参数是有变化的。
可以用format下处理:
from lxml import etree
import requests
#爬取基本的豆瓣TOP250信息
#伪装浏览器,headers可以从开发人员工具中找到User-Agent
headers={
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36'
}
def getResqutes():
urls=["https://movie.douban.com/top250?start={}".format(str(i)) for i in range(0,250,25)]
for url in urls:
data=requests.get(url,headers=headers) #此处是请求
html=etree.HTML(data.text) #网页的解析
count=html.xpath("//div[@class='item']") #这里是共有的xpath
for info in count:
title=info.xpath("div[2]/div[1]/a/span[1]/text()")#电影名称
start=info.xpath("div[2]/div[2]/div/span[2]/text()")#电影星评
detail=info.xpath("div[2]/div[2]/p[2]/span/text()") #电影的简介
for title,start,detail in zip(title,start,detail):
result={
"title":title,
"start":start,
"detail":detail,
}
print(result)
if __name__=='__main__':
getResqutes()
注意:
很多人不明白xpath的是怎么选取元素
官方网站:http://www.w3school.com.cn/xpath/index.asp
按照上面的我给的例子:
start星评:
直接从网上拿到xpath是这样的,那我们分析:
//*[@id="content"]/div/div[1]/ol/li[3]/div/div[2]/div[2]/div/span[2]
//div[@class='item'] 是共有的,很明显,li[3]之前的全部不用,li[3]后面的那个div就是div[@class="item"]
div[2]/div[2]/div/span[2] 才是我们要的
那start=info.xpath("div[2]/div[2]/div/span[2]")
爬取之后的数据
版权声明:本文为博主原创文章,未经博主允许不得转载。https://mp.csdn.net/postedit/81105232
除特别声明,本站所有文章均为原创,如需转载请以超级链接形式注明出处:SmartCat's Blog
上一篇: 问题解决方法论(解决bug)
下一篇: python相关工具使用技巧(pip)
精华推荐