使用python做最简单的爬虫
生活随笔
收集整理的這篇文章主要介紹了
使用python做最简单的爬虫
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
使用python做最簡單的爬蟲
--之心
#第一種方法import urllib2 #將urllib2庫引用進(jìn)來
response=urllib2.urlopen("http://www.baidu.com") #調(diào)用庫中的方法,將請求回應(yīng)封裝到response對象中
html=response.read() #調(diào)用response對象的read()方法,將回應(yīng)字符串賦給hhtml變量
print html #打印出來
#第二中方法
import urllib2
req=urllib2.Request("http://ww.baidu.com")
response=urllib2.urlopen(req)
html = response.read()
print html
一般情況下,上面的爬蟲,如果大量爬行,會被限制訪問,所以要偽裝成瀏覽器進(jìn)行訪問
這里用偽裝成IE9.0進(jìn)行訪問
#要求請的url地址
import urllib2
url="http://www.baidu.com"
#要偽裝的瀏覽器user_agent頭
user_agent="Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36;"
#創(chuàng)建字典,使請求的headers中的’User-Agent‘:對應(yīng)user_agent字符串
headers={'User-Agent':user_agent}
#新建一個(gè)請求,將請求中的headers變換成自己定義的
req =urllib2.Request(url,headers=headers)
#請求服務(wù)器,得到回應(yīng)
response=urllib2.urlopen(req)
#得到回應(yīng)內(nèi)容
the_page=response.read()
#打印結(jié)果
print the_page
轉(zhuǎn)載于:https://www.cnblogs.com/DaoXin-WXR/p/8012968.html
總結(jié)
以上是生活随笔為你收集整理的使用python做最简单的爬虫的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 原生android 全面屏,谷歌全面屏手
- 下一篇: websocket python爬虫_p