python使用xpath爬取豆瓣电影top 250信息
2020-05-05 22:26
197 查看
根据爬取的框架:
-导入用到的模块
-对要爬取的url,伪装ua,编码发送请求,获得响应
-将响应的信息,解析后输出,保存到本地,(进阶为分析数据,建模、预测)
#导入用的模块 from lxml import etree import requests
在写代码前,先去观察分析爬取的豆瓣电影的界面信息结构,250条记录,一共10页,每页25条,包括电影名称、评分、评论、电影连接、影片描述;
先观察单条信息的html代码,找到规律,获取xpath;
再观察如何能一次性print出250条,既然分10页,那就用for循环即可;
再思考是否所有的电影信息都有内容呢,是否会有None或者NULL,此时该如何处理;
#经过一番思考(资料学习),最终得出 for a in range(10): url = 'https://movie.douban.com/top250?start={}'.format(a*25) ua = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.122 Safari/537.36' with requests.get(url,headers={'User-Agent':ua}) as response: content = response.text html = etree.HTML(content) #分析HTML,返回DOM根节点 file = html.xpath('//*[@id="content"]/div/div[1]/ol/li') #爬取每部电影的孤立信息时,找到可以覆盖整部电影的标签,避免因匹配出现的错误 for div in file: title = div.xpath('./div/div[2]/div[1]/a/span[1]/text()')[0]#返回文本列表,列表只有一个值,对其取第一个值就可以 href= div.xpath('./div/div[2]/div[1]/a/@href')[0] score = div.xpath('./div/div[2]/div[2]/div/span[2]/text()')[0] scripe = div.xpath('./div/div[2]/div[2]/p[2]/span/text()') num = div.xpath('./div/div[2]/div[2]/div/span[4]/text()')[0].strip('(').strip().strip(')') #strip() 方法,() 里面表示要删除的内容,strip(’(’) 表示删除括号,strip() 表示删除空白符 #print('{},{},{},{},{}'.format(title,href,score,num,scripe[0])) if len(scripe) > 0: print('{},{},{},{},{}'.format(title,href,score,num,scripe[0])) else : print('{},{},{},{}'.format(title,href,score,num))
相关文章推荐
- 使用Python3.5爬取豆瓣电影Top250
- python爬虫——爬取豆瓣top250电影信息
- python3 用xpath方法爬取豆瓣电影top250(排名,名称,演员表,评分,短评)
- [151116 记录] 使用Python3.5爬取豆瓣电影Top250
- [python爬虫] BeautifulSoup和Selenium对比爬取豆瓣Top250电影信息
- [Python/爬虫]利用xpath爬取豆瓣电影top250
- python爬虫(一)爬取豆瓣电影Top250
- 如何用Python在豆瓣中获取自己喜欢的TOP N电影信息
- 实践Python的爬虫框架Scrapy来抓取豆瓣电影TOP250
- Python爬虫豆瓣电影top250
- Python爬取豆瓣电影top250
- 运维学python之爬虫高级篇(五)scrapy爬取豆瓣电影TOP250
- Python网络爬虫:利用正则表达式爬取豆瓣电影top250排行前10页电影信息
- python爬虫 豆瓣电影top250
- Python爬取豆瓣电影top250
- Python爬虫学习笔记(3) _豆瓣电影TOP250(3)采用sql存储的方法爬取豆瓣电影
- python实战爬取豆瓣电影top250
- 带你用Python爬取豆瓣电影Top250
- 超简单的豆瓣电影Top前250影片基本信息爬取
- Python 爬取豆瓣电影Top250(一)