python怎么爬网站资源_分享十种py3爬取网页资源的方法

这两天学习了python3实现抓取网页资源的方法,发现了很多种方法,所以,今天添加一点小笔记。

这两天学习了python3实现抓取网页资源的方法,发现了很多种方法,所以,今天添加一点小笔记。

1、最简单import urllib.request

response = urllib.request.urlopen('http://python.org/')

html = response.read()

2、使用 Requestimport urllib.request

req = urllib.request.Request('http://python.org/')

response = urllib.request.urlopen(req)

the_page = response.read()

3、发送数据#! /usr/bin/env python3

import urllib.parse

import urllib.request

url = 'http://localhost/login.php'

user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'

values = {

'act' : 'login',

'login[email]' : 'yzhang@i9i8.com',

'login[password]' : '123456'

}

data = urllib.parse.urlencode(values)

req = urllib.request.Request(url, data)

req.add_header('Referer', 'http://www.python.org/')

response = urllib.request.urlopen(req)

the_page = response.read()

print(the_page.decode("utf8"))

4、发送数据和header#! /usr/bin/env python3

import urllib.parse

import urllib.request

url = 'http://localhost/login.php'

user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'

values = {

'act' : 'login',

'login[email]' : 'yzhang@i9i8.com',

'login[password]' : '123456'

}

headers = { 'User-Agent' : user_agent }

data = urllib.parse.urlencode(values)

req = urllib.request.Request(url, data, headers)

response = urllib.request.urlopen(req)

the_page = response.read()

print(the_page.decode("utf8"))

5、http 错误#! /usr/bin/env python3

import urllib.request

req = urllib.request.Request('http://www.python.org/fish.html')

try:

urllib.request.urlopen(req)

except urllib.error.HTTPError as e:

print(e.code)

print(e.read().decode("utf8"))

6、异常处理1#! /usr/bin/env python3

from urllib.request import Request, urlopen

from urllib.error import URLError, HTTPError

req = Request("http://twitter.com/")

try:

response = urlopen(req)

except HTTPError as e:

print('The server couldn\'t fulfill the request.')

print('Error code: ', e.code)

except URLError as e:

print('We failed to reach a server.')

print('Reason: ', e.reason)

else:

print("good!")

print(response.read().decode("utf8"))

7、异常处理2#! /usr/bin/env python3

from urllib.request import Request, urlopen

from urllib.error import URLError

req = Request("http://twitter.com/")

try:

response = urlopen(req)

except URLError as e:

if hasattr(e, 'reason'):

print('We failed to reach a server.')

print('Reason: ', e.reason)

elif hasattr(e, 'code'):

print('The server couldn\'t fulfill the request.')

print('Error code: ', e.code)

else:

print("good!")

print(response.read().decode("utf8"))

8、HTTP 认证#! /usr/bin/env python3

import urllib.request

# create a password manager

password_mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()

# Add the username and password.

# If we knew the realm, we could use it instead of None.

top_level_url = "https://cms.tetx.com/"

password_mgr.add_password(None, top_level_url, 'yzhang', 'cccddd')

handler = urllib.request.HTTPBasicAuthHandler(password_mgr)

# create "opener" (OpenerDirector instance)

opener = urllib.request.build_opener(handler)

# use the opener to fetch a URL

a_url = "https://cms.tetx.com/"

x = opener.open(a_url)

print(x.read())

# Install the opener.

# Now all calls to urllib.request.urlopen use our opener.

urllib.request.install_opener(opener)

a = urllib.request.urlopen(a_url).read().decode('utf8')

print(a)

9、使用代理#! /usr/bin/env python3

import urllib.request

proxy_support = urllib.request.ProxyHandler({'sock5': 'localhost:1080'})

opener = urllib.request.build_opener(proxy_support)

urllib.request.install_opener(opener)

a = urllib.request.urlopen("http://g.cn").read().decode("utf8")

print(a)

10、超时#! /usr/bin/env python3

import socket

import urllib.request

# timeout in seconds

timeout = 2

socket.setdefaulttimeout(timeout)

# this call to urllib.request.urlopen now uses the default timeout

# we have set in the socket module

req = urllib.request.Request('http://twitter.com/')

a = urllib.request.urlopen(req).read()

print(a)

【相关推荐】

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Python虫Scrapy是一种用于网站数据的工具。它可以自动化地从网站上获取数据,并将其存储在本地或远程服务器上。Scrapy使用Python编写,具有高效、灵活和可扩展的特点,可以处理大量数据和复杂的网站结构。使用Scrapy可以快速地获取所需的数据,从而为数据分析和挖掘提供支持。 ### 回答2: Python虫是一种快速、高效的网络虫工具,它利用Python语言及其强大的第三方库实现自动化取互联网信息的过程。而Scrapy是一个Python虫框架,可以帮助我们快速构建持续性的虫应用程序。 基于Scrapy框架的虫程序设计,首先需要明确自己的目标:确定目标网站、确定目标页面、确定目标信息。其次,在编写程序之前,我们需要构建好虫的数据模型,包括目标页面的结构、目标信息的抽取规则等。Scrapy框架的核心就是Spider,将会快速地处理目标页面,解析数据并且提取出所需信息。这些信息可以经过清洗、存储和分析等处理过程,最终达到我们的预期需求。 虫程序的主要步骤是: 1.创建一个Scrapy项目,包括spider、items、pipelines等。 2.定义spider,包括start_urls、parse等。 3.定义item,表示解析结果的结构。 4.定义pipeline,用于处理抓取到的数据。 5.运行虫程序并保存数据。 在使用Scrapy进行网络虫时,需要遵守相关法律法规,尊重目标网站的利益和知识产权,不进行违法、违规的操作,同时遵守robots.txt协议等规定,如不得取不允许抓取的页面。 总之,对于想要进行网络数据采集的人来说,Scrapy是一个非常强大的Python虫框架。它支持异步IO和协程等功能,可以快速、高效地提取目标数据。但是,使用Scrapy时需要遵循规则,合理利用,不进行违法、违规操作。 ### 回答3: Scrapy是基于Python语言的虫框架,它可以更好的帮我们实现网站的任务。scrapy提供了一整套虫流程和一些基本机制,比如:异步处理,中间件机制,数据管道,数据解析等等。这些机制可以帮我们更加简便和高效地进行网络取任务。 使用Scrapy网站有以下几个步骤: 1. 安装Scrapy框架 我们需要提前安装好Python和Scrapy框架。安装Scrapy比较方便,可以通过pip来安装,命令为:pip install scrapy。 2. 创建scrapy虫工程 我们需要使用scrapy startproject 项目名的命令来创建项目,并进入到项目的工程目录来创建虫内容,命令为:scrapy genspider 虫名 域名。 3. 配置scrapy虫的设置 进入到Scrapy工程目录,找到settings.py文件,修改里面的文件配置,包括:User-Agent,虫间隔时间,ip代理池设置等等。 4. 配置scrapy虫的项 在Spider中定义需要取的网站信息,包括URL地址和需要获取的数据。 5. 实现URL地址的解析 在Spider中写解析函数,对虫获取到的URL进行解析,获取需要的数据内容。 6. 虫启动 最后,使用命令scrapy crawl 虫名,启动虫。取的URL资源会被输出进行。如果取的URL过多,那么可以使用命令scrapy crawl 虫名 -o 文件名.格式名来保存虫获取到的数据内容。 总的来说,Scrapy是一个快速高效的虫框架,有着多种策略来处理不同种类的虫需求。使用Scrapy进行虫的开发,不仅能够为我们省去很多重复性工作,还能够提高我们的开发效率和虫的运行效率。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值