python爬虫学习之task1:request应用

HTTP

HTTP是一个客户端(用户)和服务器端(网站)之间进行请求和应答的标准。

通过使用网页浏览器、网络爬虫或者其他工具,客户端可以向服务器上的指定端口(默认端口为80)发起一个HTTP请求。这个客户端成为客户代理(user agent)。应答服务器上存储着一些资源码,比如HTML文件和图像。这个应答服务器成为源服务器(origin server)。在用户代理和源服务器中间可能存在多个“中间层”,比如代理服务器、网关或者隧道(tunnel)。尽管TCP/IP是互联网最流行的协议,但HTTP中并没有规定必须使用它或它支持的层。

网页基础

1.组成

网页是由 HTML 、 CSS 、JavaScript 组成的。

HTML:整个网页的框架。

CSS:层叠样式表。样式表定义如何显示 HTML 元素,就像 HTML 中的字体标签和颜色属性所起的作用那样。样式通常保存在外部的 .css 文件中。“样式”指网页中文字大小、颜色、元素间距、排列等格式。

JavaScript :实现网页的数据动态交互、网页上的动画。

2.网页结构

创建一个简单的HTML页面,显示“hello python”。

<!DOCTYPE html> 
<!--整个文档是以 DOCTYPE 来开头的-->

<html lang="en"> 
<!--%整个文档最外层的标签是 <html>-->
<!--HTML 文档一般分为 head 和 body 两个部分-->


<head>
<!--在 head 头中,一般指定当前的编码格式为 UTF-8 ,并且使用 title 来定义网页的标题,显示在浏览器的标签上-->
    <meta charset="UTF-8">
    <title>Title</title>
</head>

<body>
<!--body 中的内容一般为整个 html 文档的正文,html的标签由<h1>到<h6>六个标签构成,字体由大到小递减,
换行标签为<br>,链接使用<a>来创建,herf属性包含链接的URL地址,比如<a href="http://www.baidu.com">
一个指向百度的链接-->
    <div id="container"> <!--id 属性为元素提供在全文档内的唯一标识-->
        <div class="wrapper"> <!--class 属性提供了一种将类似元素分类的方式,常被用于语义化或格式化-->
            <h1>Hello World</h1>
            <div>Hello Python.</div>
        </div>
    </div>
</body>
</html> 
<!--结尾以 </html> 来表示闭和,不强制需要每个标签都一定要有闭和标签-->

在浏览器中打开,显示如下:

在这里插入图片描述

Request

一个网络爬虫程序最普遍的过程:

  1. 访问站点;
  2. 定位所需的信息;
  3. 得到并处理信息。

1.安装

pip install requests

2.七个方法

在这里插入图片描述request.get()用法:
在这里插入图片描述## 3.例子
分别用request.get()和python自带urllib爬取“python之禅”。

import requests
url = 'https://www.python.org/dev/peps/pep-0020/'
res = requests.get(url)
text = res.text
with open('zon_of_python.txt', 'w') as f:
    f.write(text[text.find('<pre')+28:text.find('</pre>')-1])
print(text[text.find('<pre')+28:text.find('</pre>')-1])
import urllib
url = 'https://www.python.org/dev/peps/pep-0020/'
res = urllib.request.urlopen(url).read().decode('utf-8')
print(res[res.find('<pre')+28:res.find('</pre>')-1])

输出:

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

用火狐浏览器打开金山词霸,翻译“python之禅”。打开开发者工具的network查看headers和data。

import requests

def translate(word):
    url = "http://fy.iciba.com/ajax.php?a=fy"

    data = {
        'f': 'auto',
        't': 'auto',
        'w': word,
    }
    headers = {
        'user-agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:75.0) Gecko/20100101 Firefox/75.0',
    }  # User-Agent会告诉网站服务器,访问者是通过什么工具来请求的,如果是爬虫请求,一般会拒绝,如果是用户浏览器,就会应答。
    response = requests.post(url, data=data, headers=headers)  # 发起请求
    json_data = response.json()  # 获取json数据
    # print(json_data)
    return json_data

def run(word):
    result = translate(word)['content']['out']
    print(result)
    return result

def main():
    with open('zon_of_python.txt') as f:
        zh = [run(word) for word in f]
    with open('zon_of_python_zh-CN.txt', 'w') as g:
        for i in zh:
            g.write(i + '\n')

if __name__ == '__main__':
    main()

结果:

美丽胜过丑陋。
 外显优于内隐..
 简单胜于复杂。
 复杂胜于复杂。
 平比嵌套好..
 疏而不密..
 可读性计数。
 特殊情况不足以打破规则。
 尽管实用性胜过纯度。
 错误永远不应该悄悄地过去。
除非有明确的沉默。
 面对暧昧,拒绝猜测的诱惑..
 应该有一种----最好只有一种----明显的办法来做到这一点。
 虽然这种方式一开始可能不明显,除非你是荷兰人。
 现在总比永远好。
虽然从来没有比现在更好。
 如果实施很难解释,那是个坏主意。
 如果实现很容易解释,这可能是个好主意。
 命名空间是一个伟大的想法-让我们做更多的这些!

4.豆瓣电影爬取练习

爬取豆瓣top250电影名字和海报。
注意:一开始res.status_code = 418,触发了反爬。解决方法:添加header。
代码:

import requests
import re

def parase(text):
   para = re.compile('<img.*?alt.*?src.*?class="">')
   items = re.findall(para, text)
   for item in items:
       yield item

if __name__ == '__main__':
   headers = {
       'user-agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:75.0) Gecko/20100101 Firefox/75.0',
   }
   page = [0, 25, 50, 75, 100, 125, 150, 175, 200, 225]
   for num in page:
       url = 'https://movie.douban.com/top250?start=' + str(num) + '&fliter='
       print(url)
       res = requests.get(url,headers = headers)
       text = res.text
       print(res.status_code)
       information = parase(text)
       for item in information:
           film_name = item[item.find('alt=')+4:item.find('src')-2]
           film_image = item[item.find('src=')+4:item.find('class')-2]
           print(film_name, film_image)

结果如下:

"肖申克的救赎 "https://img3.doubanio.com/view/photo/s_ratio_poster/public/p480747492.jpg
"霸王别姬 "https://img3.doubanio.com/view/photo/s_ratio_poster/public/p2561716440.jpg
"阿甘正传 "https://img9.doubanio.com/view/photo/s_ratio_poster/public/p1484728154.jpg
"这个杀手不太冷 "https://img3.doubanio.com/view/photo/s_ratio_poster/public/p511118051.jpg
"美丽人生 "https://img3.doubanio.com/view/photo/s_ratio_poster/public/p2578474613.jpg
"泰坦尼克号 "https://img9.doubanio.com/view/photo/s_ratio_poster/public/p457760035.jpg
"千与千寻 "https://img1.doubanio.com/view/photo/s_ratio_poster/public/p2557573348.jpg
"辛德勒的名单 "https://img3.doubanio.com/view/photo/s_ratio_poster/public/p492406163.jpg
"盗梦空间 "https://img9.doubanio.com/view/photo/s_ratio_poster/public/p513344864.jpg
"忠犬八公的故事 "https://img9.doubanio.com/view/photo/s_ratio_poster/public/p524964016.jpg
"海上钢琴师 "https://img9.doubanio.com/view/photo/s_ratio_poster/public/p2574551676.jpg
"楚门的世界 "https://img3.doubanio.com/view/photo/s_ratio_poster/public/p479682972.jpg
"三傻大闹宝莱坞 "https://img3.doubanio.com/view/photo/s_ratio_poster/public/p579729551.jpg
"机器人总动员 "https://img3.doubanio.com/view/photo/s_ratio_poster/public/p1461851991.jpg
"放牛班的春天 "https://img3.doubanio.com/view/photo/s_ratio_poster/public/p1910824951.jpg
"星际穿越 "https://img3.doubanio.com/view/photo/s_ratio_poster/public/p2206088801.jpg
"大话西游之大圣娶亲 "https://img9.doubanio.com/view/photo/s_ratio_poster/public/p2455050536.jpg
"熔炉 "https://img9.doubanio.com/view/photo/s_ratio_poster/public/p1363250216.jpg
"疯狂动物城 "https://img1.doubanio.com/view/photo/s_ratio_poster/public/p2315672647.jpg
"无间道 "https://img3.doubanio.com/view/photo/s_ratio_poster/public/p2564556863.jpg
"龙猫 "https://img9.doubanio.com/view/photo/s_ratio_poster/public/p2540924496.jpg
"教父 "https://img9.doubanio.com/view/photo/s_ratio_poster/public/p616779645.jpg
"当幸福来敲门 "https://img1.doubanio.com/view/photo/s_ratio_poster/public/p1312700628.jpg
"怦然心动 "https://img1.doubanio.com/view/photo/s_ratio_poster/public/p501177648.jpg
"触不可及 "https://img9.doubanio.com/view/photo/s_ratio_poster/public/p1454261925.jpg
https://movie.douban.com/top250?start=25&fliter=

后面的电影没列出来。注意一点,排行一共有10页,每页网址不同。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值