如何详细解析使用Python urllib库添加HTTP请求headers的步骤?
- 内容介绍
- 文章标签
- 相关推荐
本文共计667个文字,预计阅读时间需要3分钟。
对于请求一些网站,我们需要添加请求头才能完成网页的抓取。否则,可能会得到一些错误,无法返回抓取的网页。下面介绍两种添加请求头的方法。
方法一:借助`build_opener`和`addheaders`完成。
pythonimport urllib.request
创建一个opener对象opener=urllib.request.build_opener()
添加请求头opener.addheaders=[('User-Agent', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3')]
使用opener打开网页response=opener.open('http://example.com')
读取网页内容content=response.read()
打印网页内容print(content)
对于请求一些网站,我们需要加上请求头才可以完成网页的抓取,不然会得到一些错误,无法返回抓取的网页。下面,介绍两种添加请求头的方法。
本文共计667个文字,预计阅读时间需要3分钟。
对于请求一些网站,我们需要添加请求头才能完成网页的抓取。否则,可能会得到一些错误,无法返回抓取的网页。下面介绍两种添加请求头的方法。
方法一:借助`build_opener`和`addheaders`完成。
pythonimport urllib.request
创建一个opener对象opener=urllib.request.build_opener()
添加请求头opener.addheaders=[('User-Agent', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3')]
使用opener打开网页response=opener.open('http://example.com')
读取网页内容content=response.read()
打印网页内容print(content)
对于请求一些网站,我们需要加上请求头才可以完成网页的抓取,不然会得到一些错误,无法返回抓取的网页。下面,介绍两种添加请求头的方法。

