国产片侵犯亲女视频播放_亚洲精品二区_在线免费国产视频_欧美精品一区二区三区在线_少妇久久久_在线观看av不卡

腳本之家,腳本語言編程技術及教程分享平臺!
分類導航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服務器之家 - 腳本之家 - Python - 深入解析Python中的urllib2模塊

深入解析Python中的urllib2模塊

2020-08-03 11:21腳本之家 Python

這篇文章主要介紹了Python中的urllib2模塊,包括一個利用其抓取網站生成RSS的小例子,需要的朋友可以參考下

Python 標準庫中有很多實用的工具類,但是在具體使用時,標準庫文檔上對使用細節描述的并不清楚,比如 urllib2 這個 HTTP 客戶端庫。這里總結了一些 urllib2 的使用細節。

  • Proxy 的設置
  • Timeout 設置
  • 在 HTTP Request 中加入特定的 Header
  • Redirect
  • Cookie
  • 使用 HTTP 的 PUT 和 DELETE 方法
  • 得到 HTTP 的返回碼
  • Debug Log

Proxy 的設置

urllib2 默認會使用環境變量 http_proxy 來設置 HTTP Proxy。如果想在程序中明確控制 Proxy 而不受環境變量的影響,可以使用下面的方式

?
1
2
3
4
5
6
7
8
9
10
11
import urllib2
enable_proxy = True
proxy_handler = urllib2.ProxyHandler({"http" : 'http://some-proxy.com:8080'})
null_proxy_handler = urllib2.ProxyHandler({})
 
if enable_proxy:
opener = urllib2.build_opener(proxy_handler)
else:
opener = urllib2.build_opener(null_proxy_handler)
 
urllib2.install_opener(opener)

這里要注意的一個細節,使用 urllib2.install_opener() 會設置 urllib2 的全局 opener 。這樣后面的使用會很方便,但不能做更細粒度的控制,比如想在程序中使用兩個不同的 Proxy 設置等。比較好的做法是不使用 install_opener 去更改全局的設置,而只是直接調用 opener 的 open 方法代替全局的 urlopen 方法。

Timeout 設置

在老版 Python 中,urllib2 的 API 并沒有暴露 Timeout 的設置,要設置 Timeout 值,只能更改 Socket 的全局 Timeout 值。

?
1
2
3
4
5
6
import urllib2
 
 
import socket
socket.setdefaulttimeout(10) # 10 秒鐘后超時
urllib2.socket.setdefaulttimeout(10) # 另一種方式

在 Python 2.6 以后,超時可以通過 urllib2.urlopen() 的 timeout 參數直接設置。

?
1
2
import urllib2
response = urllib2.urlopen('http://www.google.com', timeout=10)

在 HTTP Request 中加入特定的 Header

要加入 header,需要使用 Request 對象:

?
1
2
3
4
import urllib2
request = urllib2.Request(uri)
request.add_header('User-Agent', 'fake-client')
response = urllib2.urlopen(request)

對有些 header 要特別留意,服務器會針對這些 header 做檢查

User-Agent : 有些服務器或 Proxy 會通過該值來判斷是否是瀏覽器發出的請求

Content-Type : 在使用 REST 接口時,服務器會檢查該值,用來確定 HTTP Body 中的內容該怎樣解析。常見的取值有:

  • application/xml : 在 XML RPC,如 RESTful/SOAP 調用時使用
  • application/json : 在 JSON RPC 調用時使用
  • application/x-www-form-urlencoded : 瀏覽器提交 Web 表單時使用

在使用服務器提供的 RESTful 或 SOAP 服務時, Content-Type 設置錯誤會導致服務器拒絕服務

Redirect

urllib2 默認情況下會針對 HTTP 3XX 返回碼自動進行 redirect 動作,無需人工配置。要檢測是否發生了 redirect 動作,只要檢查一下 Response 的 URL 和 Request 的 URL 是否一致就可以了。

?
1
2
3
import urllib2
response = urllib2.urlopen('http://www.google.cn')
redirected = response.geturl() == 'http://www.google.cn'

如果不想自動 redirect,除了使用更低層次的 httplib 庫之外,還可以自定義 HTTPRedirectHandler 類。

?
1
2
3
4
5
6
7
8
9
10
import urllib2
 
class RedirectHandler(urllib2.HTTPRedirectHandler):
def http_error_301(self, req, fp, code, msg, headers):
pass
def http_error_302(self, req, fp, code, msg, headers):
pass
 
opener = urllib2.build_opener(RedirectHandler)
opener.open('http://www.google.cn')

Cookie

urllib2 對 Cookie 的處理也是自動的。如果需要得到某個 Cookie 項的值,可以這么做:

?
1
2
3
4
5
6
7
8
9
import urllib2
import cookielib
 
cookie = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie))
response = opener.open('http://www.google.com')
for item in cookie:
if item.name == 'some_cookie_item_name':
print item.value

使用 HTTP 的 PUT 和 DELETE 方法

urllib2 只支持 HTTP 的 GET 和 POST 方法,如果要使用 HTTP PUT 和 DELETE ,只能使用比較低層的 httplib 庫。雖然如此,我們還是能通過下面的方式,使 urllib2 能夠發出 PUT 或 DELETE 的請求:

?
1
2
3
4
5
import urllib2
 
request = urllib2.Request(uri, data=data)
request.get_method = lambda: 'PUT' # or 'DELETE'
response = urllib2.urlopen(request)

得到 HTTP 的返回碼

對于 200 OK 來說,只要使用 urlopen 返回的 response 對象的 getcode() 方法就可以得到 HTTP 的返回碼。但對其它返回碼來說,urlopen 會拋出異常。這時候,就要檢查異常對象的 code 屬性了:

?
1
2
3
4
5
6
import urllib2
try:
response = urllib2.urlopen('http://restrict.web.com')
except urllib2.HTTPError, e:
print e.code
Debug Log

使用 urllib2 時,可以通過下面的方法把 debug Log 打開,這樣收發包的內容就會在屏幕上打印出來,方便調試,有時可以省去抓包的工作

?
1
2
3
4
5
6
7
8
import urllib2
 
httpHandler = urllib2.HTTPHandler(debuglevel=1)
httpsHandler = urllib2.HTTPSHandler(debuglevel=1)
opener = urllib2.build_opener(httpHandler, httpsHandler)
 
urllib2.install_opener(opener)
response = urllib2.urlopen('http://www.google.com')

PS: 借助urllib2抓取網站生成RSS
看了看OsChina的博客頁面,發現可以使用python來抓取.記得前段時間看到有人使用python的RSS模塊PyRSS2Gen生成了RSS.于是忍不住手癢自己試著實現了下,幸好還是成功了,下面代碼共享給大家.
首先需要安裝PyRSS2Gen模塊和BeautifulSoup模塊,pip安裝下就好了,我就不再贅述了.
下面貼出代碼

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# -*- coding: utf-8 -*-
 
 
from bs4 import BeautifulSoup
import urllib2
 
import datetime
import time
import PyRSS2Gen
from email.Utils import formatdate
import re
import sys
import os
reload(sys)
sys.setdefaultencoding('utf-8')
 
 
 
 
class RssSpider():
  def __init__(self):
    self.myrss = PyRSS2Gen.RSS2(title='OSChina',
                  link='http://my.oschina.net',
                  description=str(datetime.date.today()),
                  pubDate=datetime.datetime.now(),
                  lastBuildDate = datetime.datetime.now(),
                  items=[]
                  )
    self.xmlpath=r'/var/www/myrss/oschina.xml'
 
    self.baseurl="http://www.oschina.net/blog"
    #if os.path.isfile(self.xmlpath):
      #os.remove(self.xmlpath)
  def useragent(self,url):
    i_headers = {"User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) \
  AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.125 Safari/537.36", \
  "Referer": 'http://baidu.com/'}
    req = urllib2.Request(url, headers=i_headers)
    html = urllib2.urlopen(req).read()
    return html
  def enterpage(self,url):
    pattern = re.compile(r'\d{4}\S\d{2}\S\d{2}\s\d{2}\S\d{2}')
    rsp=self.useragent(url)
    soup=BeautifulSoup(rsp)
    timespan=soup.find('div',{'class':'BlogStat'})
    timespan=str(timespan).strip().replace('\n','').decode('utf-8')
    match=re.search(r'\d{4}\S\d{2}\S\d{2}\s\d{2}\S\d{2}',timespan)
    timestr=str(datetime.date.today())
    if match:
      timestr=match.group()
      #print timestr
    ititle=soup.title.string
    div=soup.find('div',{'class':'BlogContent'})
    rss=PyRSS2Gen.RSSItem(
               title=ititle,
               link=url,
               description = str(div),
               pubDate = timestr
               )
 
    return rss
  def getcontent(self):
    rsp=self.useragent(self.baseurl)
    soup=BeautifulSoup(rsp)
    ul=soup.find('div',{'id':'RecentBlogs'})
    for li in ul.findAll('li'):
      div=li.find('div')
      if div is not None:
        alink=div.find('a')
        if alink is not None:
          link=alink.get('href')
          print link
          html=self.enterpage(link)
          self.myrss.items.append(html)
  def SaveRssFile(self,filename):
    finallxml=self.myrss.to_xml(encoding='utf-8')
    file=open(self.xmlpath,'w')
    file.writelines(finallxml)
    file.close()
 
 
 
if __name__=='__main__':
  rssSpider=RssSpider()
  rssSpider.getcontent()
  rssSpider.SaveRssFile('oschina.xml')

可以看到,主要是使用BeautifulSoup來抓取站點然后使用PyRSS2Gen來生成RSS并保存為xml格式文件.
順便共享下我生成的RSS地址

?
1
http://104.224.129.109/myrss/oschina.xml

大家如果不想折騰的話直接使用feedly訂閱就行了.
腳本我會每10分鐘執行一次的.

延伸 · 閱讀

精彩推薦
Weibo Article 1 Weibo Article 2 Weibo Article 3 Weibo Article 4 Weibo Article 5 Weibo Article 6 Weibo Article 7 Weibo Article 8 Weibo Article 9 Weibo Article 10 Weibo Article 11 Weibo Article 12 Weibo Article 13 Weibo Article 14 Weibo Article 15 Weibo Article 16 Weibo Article 17 Weibo Article 18 Weibo Article 19 Weibo Article 20 Weibo Article 21 Weibo Article 22 Weibo Article 23 Weibo Article 24 Weibo Article 25 Weibo Article 26 Weibo Article 27 Weibo Article 28 Weibo Article 29 Weibo Article 30 Weibo Article 31 Weibo Article 32 Weibo Article 33 Weibo Article 34 Weibo Article 35 Weibo Article 36 Weibo Article 37 Weibo Article 38 Weibo Article 39 Weibo Article 40
主站蜘蛛池模板: 啊啊啊网站 | 依人在线 | 久久国产一区二区 | 久草视频国产 | 欧美一级欧美三级在线观看 | 亚洲欧美在线观看 | 日本综合色 | 欧美一区二区三区电影 | 精彩毛片 | 亚洲视频在线一区 | 91污在线观看 | 精产国产伦理一二三区 | 日本黄色一区 | 羞羞的网站| 91一区二区在线 | 成人av电影网址 | 夜夜操天天干, | 日韩精品一区二区三区中文字幕 | 成人精品国产一区二区4080 | 久久亚洲天堂 | 国内精品久久久久久中文字幕 | 久久精品国产亚洲一区二区三区 | 欧美另类视频在线 | 中文字幕不卡 | 激情五月综合网 | 亚洲精品乱码久久久久久蜜桃不爽 | 精品国产青草久久久久福利 | 亚洲一区中文字幕 | 免费成人福利视频 | av免费影视 | 欧美一区二区三区在线观看视频 | 视频在线一区 | 精品视频在线免费观看 | 国内久久精品 | 高清一区二区三区视频 | 最近最新mv字幕免费观看 | 久久久国产一区 | 欧美透逼 | 国产三级在线观看 | 日韩av一区二区在线观看 | 免费羞羞视频网站 |