python3简单爬虫,访问百度

前几天把python基础看完,自己动手做了个小练习,写下这篇博客留作纪念。以下代码简单写了三种方式去访问百度界面并且拿到页面的数据(源码),由于页面数据太多,所以只打出了页面的长度。

# python3中用urllib.request表示python2中的urllib2
import urllib.request as urllib2
# python3中用http.cookiejar表示python2中的cookielib
import http.cookiejar as cookielib

print ("第一种方式")
# 需要访问的url
url="https://www.baidu.com"
response=urllib2.urlopen(url)
# 返回一个数值结果,200表示正常
print (response.getcode())
# print(response.read().decode('utf-8'))    打印整个页面
# 打出页面的长度
print (len(response.read()))


print('第二种方式')
#伪装成浏览器对页面进行访问
request=urllib2.Request(url)
request.add_header("user-agent","Mozilla/5.0 (Windows NT 6.1; WOW64; rv:53.0) Gecko/20100101 Firefox/53.0")
response1=urllib2.urlopen(request)
print (response1.getcode())
print (len(response1.read()))


print ("第三种方式")
#针对需要登录的网页
cj=cookielib.CookieJar()
opener=urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
urllib2.install_opener(opener)
response3=urllib2.urlopen(url)
print (response3.getcode())
print (len(response3.read()))

 如有疑问,欢迎提问,本人定当竭尽所能为您解答

猜你喜欢

转载自blog.csdn.net/weixin_40169642/article/details/82420876