Python 3 抓取网页资源的 N 种方法

简介: 1、最简单 import urllib.requestresponse = urllib.request.urlopen('http://python.org/')html = response.
1、最简单
import urllib.request
response = urllib.request.urlopen( ' http://python.org/ ')
html = response.read()
2、使用 Request
import 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)
复制代码

 
 
相关文章
|
2月前
|
数据采集 Web App开发 JavaScript
基于Selenium的Python爬虫抓取动态App图片
基于Selenium的Python爬虫抓取动态App图片
250 68
|
2月前
|
Web App开发 数据采集 JavaScript
动态网页爬取:Python如何获取JS加载的数据?
动态网页爬取:Python如何获取JS加载的数据?
421 58
|
2月前
|
API 开发工具 网络架构
【Azure Service Bus】使用Python SDK创建Service Bus Namespace资源(中国区)
本文介绍了如何使用Python SDK创建Azure Service Bus Namespace资源。首先,通过Microsoft Entra ID注册应用获取Client ID、Client Secret和Tenant ID,完成中国区Azure认证。接着,初始化ServiceBusManagementClient对象,并调用`begin_create_or_update`方法创建资源。
88 29
|
2月前
|
Python
Python技术解析:了解数字类型及数据类型转换的方法。
在Python的世界里,数字并不只是简单的数学符号,他们更多的是一种生动有趣的语言,用来表达我们的思维和创意。希望你从这个小小的讲解中学到了有趣的内容,用Python的魔法揭示数字的奥秘。
82 26
|
1月前
|
JSON 数据格式 Python
解决Python requests库POST请求参数顺序问题的方法。
总之,想要在Python的requests库里保持POST参数顺序,你要像捋顺头发一样捋顺它们,在向服务器炫耀你那有条不紊的数据前。抓紧手中的 `OrderedDict`与 `json`这两把钥匙,就能向服务端展示你的请求参数就像经过高端配置的快递包裹,里面的商品摆放井井有条,任何时候开箱都是一种享受。
56 10
|
1月前
|
数据采集 Web App开发 JavaScript
Python爬虫解析动态网页:从渲染到数据提取
Python爬虫解析动态网页:从渲染到数据提取
|
2月前
|
Python
Python 中__new__方法详解及使用
__new__ 是 Python 中用于创建类实例的静态方法,在实例化对象时优先于 __init__ 执行。它定义在基础类 object 中,需传递 cls 参数(表示当前类)。__new__ 可决定是否使用 __init__ 方法或返回其他对象作为实例。特性包括:1) 在实例化前调用;2) 始终为静态方法。示例中展示了其用法及 Python2 和 Python3 的差异,强调了参数处理的不同。
109 10
|
2月前
|
数据采集 存储 前端开发
Python爬虫自动化:批量抓取网页中的A链接
Python爬虫自动化:批量抓取网页中的A链接
|
2月前
|
人工智能 Ruby Python
python__init__方法笔记
本文总结了Python中`__init__`方法的使用要点,包括子类对父类构造方法的调用规则。当子类未重写`__init__`时,实例化会自动调用父类的构造方法;若重写,则需通过`super()`或直接调用父类名称来显式继承父类初始化逻辑。文中通过具体代码示例展示了不同场景下的行为及输出结果,帮助理解类属性与成员变量的关系,以及如何正确使用`super()`实现构造方法的继承。
103 9
|
2月前
|
存储 索引 Python
[oeasy]python093_find方法_指数为负数_index_实际效果
本文介绍了Python中`find`方法与索引(index)的使用,包括负数索引的实际效果。回顾了`eval`函数的应用,并强调类名如`str`、`int`、`list`不可用作变量名以避免覆盖。通过示例解析了负数索引在字符串和列表中的作用,以及`index`方法的三个参数(value、start、stop)的用法。同时对比了`index`和`find`方法的区别:`index`找不到子串时抛出`ValueError`,而`find`返回-1。最后总结了正负索引的使用场景及两者的特性,提供了相关学习资源链接。
310 8

推荐镜像

更多