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天前
|
存储 Linux Shell
python移除/删除非空文件夹/目录的最有效方法是什么?
python移除/删除非空文件夹/目录的最有效方法是什么?
7 0
|
4天前
|
Python
【Python 基础】Python中的实例方法、静态方法和类方法有什么区别?
【5月更文挑战第6天】【Python 基础】Python中的实例方法、静态方法和类方法有什么区别?
|
4天前
|
数据处理 Python
Python中每个字段增加多条数据的高效方法
Python中每个字段增加多条数据的高效方法
10 1
|
4天前
|
数据采集 存储 JavaScript
使用Python截取网页内容的综合指南
使用Python截取网页内容的综合指南
20 1
|
5天前
|
存储 数据挖掘 Python
Python技术分享:实现选择文件或目录路径的方法
Python技术分享:实现选择文件或目录路径的方法
15 2
|
5天前
|
数据处理 Python
Python中按指定数量分割列表字符串的方法
Python中按指定数量分割列表字符串的方法
9 1
|
5天前
|
前端开发 JavaScript Python
使用Python读取本地行情csv文件,做出web网页画出K线图实现案例
【5月更文挑战第4天】使用Python绘制K线图的步骤:1) 安装pandas, matplotlib和Flask;2) 用pandas读取CSV文件并处理数据;3) 创建Flask应用,渲染包含K线图数据的HTML;4) 编写HTML,使用ECharts库绘制K线图。
23 0
|
9天前
|
Python
使用Python pandas的sort_values()方法可按一个或多个列对DataFrame排序
使用Python pandas的sort_values()方法可按一个或多个列对DataFrame排序。示例代码展示了如何按'Name'和'Age'列排序 DataFrame。先按'Name'排序,再按'Age'排序。sort_values()的by参数接受列名列表,ascending参数控制排序顺序(默认升序),inplace参数决定是否直接修改原DataFrame。
21 1
|
10天前
|
机器学习/深度学习 数据可视化 前端开发
【Python机器学习专栏】机器学习模型评估的实用方法
【4月更文挑战第30天】本文介绍了机器学习模型评估的关键方法,包括评估指标(如准确率、精确率、召回率、F1分数、MSE、RMSE、MAE及ROC曲线)和交叉验证技术(如K折交叉验证、留一交叉验证、自助法)。混淆矩阵提供了一种可视化分类模型性能的方式,而Python的scikit-learn库则方便实现这些评估。选择适合的指标和验证方法能有效优化模型性能。
|
10天前
|
机器学习/深度学习 算法 Python
【Python机器学习专栏】Python中的特征选择方法
【4月更文挑战第30天】本文介绍了机器学习中特征选择的重要性,包括提高模型性能、减少计算成本和增强可解释性。特征选择方法主要包括过滤法(如相关系数、卡方检验和互信息)、包装法(如递归特征消除和顺序特征选择)和嵌入法(如L1正则化和决策树)。在Python中,可利用`sklearn`库的`feature_selection`模块实现这些方法。通过有效的特征选择,能构建更优的模型并深入理解数据。