首页 技术 正文
技术 2022年11月14日
0 收藏 543 点赞 4,328 浏览 1412 个字

一个很简单的爬虫。

从这里学习的,解释的挺好的:https://xlzd.me/2015/12/16/python-crawler-03

分享写这个代码用到了的学习的链接:

BeautifulSoup官方文档

requests文档

codecs

with……as……的解释

.join函数

.format函数

其他的一些东西在代码里面有详细注释。

 # encoding = utf-8
import codecs
import requests
from bs4 import BeautifulSoup # 爬取豆瓣电影TOP250 DOWNLOADURL = 'https://movie.douban.com/top250' def download_page(url): # 向服务器发送请求下载得到html
headers = {'User-Agent': 'Mozilla/4.0(compatibel; MSIE 5.5; Windows NT)'} # 伪装成浏览器
data = requests.get(url, headers=headers).content
return data # 返回得到的html代码 def parse_html(html): # 解析网页
soup = BeautifulSoup(html, 'lxml') # 创建一个BeautifulSoup对象
movie_list_soup = soup.find('ol', attrs={'class': 'grid_view'}) # 定位 name_list = []
for movie_li in movie_list_soup.find_all('li'): # 找到电影名字
detail = movie_li.find('div', attrs={'class', 'hd'})
movie_name = detail.find('span', attrs={'class', 'title'}).getText()
name_list.append(movie_name) # 放到一个list里面 have_next = soup.find('span', attrs={'class': 'next'}).find('a') # 找下一页的链接
if have_next: # 如果有下一页的链接不为空
return name_list, DOWNLOADURL + have_next['href'] # 返回名字列表还有下一页的URL
else:
return name_list, None # 找不到返回None def main():
url = DOWNLOADURL
# with xxx.open as f 打开xxx之后finally关闭xxx
# codecs方便处理中文编码
with codecs.open('douban_movies', 'wb', encoding='utf-8') as fp:
while url:
html = download_page(url)
name_list, url = parse_html(html)
#'\n'.join(name_list) : 以'\n'为分隔符将name_list所有元素合并成一个新的字符串
#'{movies}'.format(movies='xxxxx') : 即movies = 'xxxxx',将xxxxx按照格式输出
fp.write(u'{movies}\n'.format(movies='\n'.join(name_list))) if __name__ == '__main__':
main()
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,488
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,903
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,737
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,489
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,128
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,290