python爬虫初学者2
2020-04-02 08:03
881 查看
代码内容 By ywz2008008
上一篇内容读出了页面的内容,虽然乱乱的一团,但还是成功了。
今天继续读出精准的内容,重点用到了:BeautifulSoup、lxml模块。
#!/usr/bin/python # -*- coding: UTF-8 -*- import requests from bs4 import BeautifulSoup movie_url = 'https://movie.douban.com/subject/1292052/' def download_page(url): headers = { 'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_12)AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.80 Safari/537.36' } data = requests.get(url, headers = headers).content return data def paser_html(html): soup = BeautifulSoup(html, 'lxml') title = soup.find(property = 'v:itemreviewed').string return title def main(): print(paser_html(download_page(movie_url))) if __name__ == '__main__': main()
结果:
肖申克的救赎 The Shawshank Redemption
取其他的内容该怎么办呢?接着问度娘……
做了个小改动:
import requests from bs4 import BeautifulSoup movie_url = 'https://movie.douban.com/subject/1292052/' def download_page(url): headers = { 'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_12)AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.80 Safari/537.36' } data = requests.get(url, headers = headers).content return data def paser_html(html): soup = BeautifulSoup(html, 'lxml') soup = soup.find(id = 'info') li_all = soup.find_all(attrs={'class':'pl'}) content_all = soup.find_all(attrs={'class':'attrs'}) for content_all in content_all: print(content_all.text) def main(): paser_html(download_page(movie_url)) if __name__ == '__main__': main()
运行结果:
========= RESTART: C:\Users\Administrator.USER-20190824JP\Desktop\2.py ========= 弗兰克·德拉邦特 弗兰克·德拉邦特 / 斯蒂芬·金 蒂姆·罗宾斯 / 摩根·弗里曼 / 鲍勃·冈顿 / 威廉姆·赛德勒 / 克兰西·布朗 / 吉尔·贝罗斯 / 马克·罗斯顿 / 詹姆斯·惠特摩 / 杰弗里·德曼 / 拉里·布兰登伯格 / 尼尔·吉恩托利 / 布赖恩·利比 / 大卫·普罗瓦尔 / 约瑟夫·劳格诺 / 祖德·塞克利拉 / 保罗·麦克兰尼 / 芮妮·布莱恩 / 阿方索·弗里曼 / V·J·福斯特 / 弗兰克·梅德拉诺 / 马克·迈尔斯 / 尼尔·萨默斯 / 耐德·巴拉米 / 布赖恩·戴拉特 / 唐·麦克马纳斯 >>>
soup = soup.find(id = 'info') li_all = soup.find_all(attrs={'class':'pl'})
重点是通过id或者属性去找想要的内容,find只能找到一个,find_all是找到所有的。
python的循环还是蛮有趣的,跟C的不一样。
还有那个if name == ‘main’: 什么意思,到现在也不太懂。
- 点赞
- 收藏
- 分享
- 文章举报
相关文章推荐
- python初学者笔记——爬虫requests
- python初学者学习笔记(一)简单的爬虫
- python爬虫初学者5之COOKIE&GBK
- python爬虫初学者4之306F12-COOKIE
- python爬虫初学者3之306F12-标签
- python爬虫初学者常用库BeautifulSoup的简单介绍
- python初学者——一个简单的网络爬虫
- Python爬虫初学者学习笔记(带注释)
- Python初学者之网络爬虫(二)
- [置顶] 初学者python爬虫(12306)
- Python初学者之网络爬虫
- 非常全面到位的介绍与源代码地址 :Python 网页爬虫 & 文本处理 & 科学计算 & 机器学习 & 数据挖掘兵器谱
- Python爬虫精进-第6关-爬到的数据存在哪里?-CSV&Excel
- Python爬虫 --爬取2016里约奥运会参赛运动员信息
- Python爬虫(3),Python3.x
- python爬虫爬取好看的图片
- python爬虫实例——爬取智联招聘信息
- Python爬虫系列(四):Beautiful Soup解析HTML之把HTML转成Python对象
- Python爬虫(bs4)-3
- Python爬虫入门一