使用python做最簡單的爬蟲
--之心
#第一種方法
import urllib2 #將urllib2庫引用進來
response=urllib2.urlopen("http://www.baidu.com") #調用庫中的方法,將請求回應封裝到response對象中
html=response.read() #調用response對象的read()方法,將回應字符串賦給hhtml變量
print html #打印出來
#第二中方法
import urllib2
req=urllib2.Request("http://ww.baidu.com")
response=urllib2.urlopen(req)
html = response.read()
print html
一般情況下,上面的爬蟲,如果大量爬行,會被限制訪問,所以要偽裝成瀏覽器進行訪問
這里用偽裝成IE9.0進行訪問
#要求請的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;"
#創建字典,使請求的headers中的’User-Agent‘:對應user_agent字符串
headers={'User-Agent':user_agent}
#新建一個請求,將請求中的headers變換成自己定義的
req =urllib2.Request(url,headers=headers)
#請求服務器,得到回應
response=urllib2.urlopen(req)
#得到回應內容
the_page=response.read()
#打印結果
print the_page