爬虫—urllib的用法

快速爬取一个网页

import urllib.request

url = 'http://www.baidu.com/'

response = urllib.request.urlopen(url=url)

html = response.read()
print(html)

with open("baidu.html", 'w') as f:
    f.write(html.decode())

看我们的地址爬下来后就是在本地

实现本地百度.png

浏览器的模拟

应用场景:有些网页为了防止别人恶意采集其信息所以进行了一些反爬虫的设置,而我们又想进行爬取。
解决方法:设置一些Headers信息(User-Agent),模拟成浏览器去访问这些网站。

import urllib.request

url = "http://www.baidu.com"

headers = {
    'User-Agent': 'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0'
}
request = urllib.request.Request(url=url, headers=headers)

response = urllib.request.urlopen(request)

print(response.read().decode())

Cookie的使用:

应用场景:爬取的网页涉及登录信息。访问每一个互联网页面,都是通过HTTP协议进行的,而HTTP协议是一个无状态协议,所谓的无状态协议即无法维持会话之间的状态。

from http import cookiejar
import urllib.request
import urllib.parse

cookiejar = cookiejar.CookieJar()

cookiejar_handler = urllib.request.HTTPCookieProcessor(cookiejar)
opener = urllib.request.build_opener(cookiejar_handler)

url = "http://www.renren.com/PLogin.do"

data = {
    "email": "[email protected]",
    "password": "123456789"
}

params = urllib.parse.urlencode(data).encode()

request = urllib.request.Request(url=url, data=params)
response = opener.open(request)
# content = response.read().decode()

opener.open(request)

request1 = urllib.request.Request(url="http://zhibo.renren.com/anchor/965358670")
response = opener.open(request1)

with open("cookiejarrenren.html", "w") as f:
    f.write(response.read().decode())

你可能感兴趣的:(爬虫—urllib的用法)