Python 爬虫 – 使用requests抓取网页

Python中,requests库可用于向web服务器发出http请求,http请求有多种方式,例如,GET/POST/PUT/DELETE 等等。

这里将使用GET请求抓取页面:

<code>import requests
page = requests.get("https://kevinhwu.github.io/demo/python-scraping/simple.html")
page
/<code>

复制

输出

<code><response>
/<response>/<code>

复制

发出请求之后,会返回一个响应对象。该对象包含一个status_code属性,表示页面访问是否成功:

<code>page.status_code
/<code>

复制

输出

<code>200
/<code>

复制

status_code为200,表示成功。关于http状态码,以2开头的状态代码通常表示成功,以4或5开头的代码表示错误,如需进一步了解,可参考相关资料。

可以使用content属性,打印出页面的HTML内容:

<code>page.content
/<code>

复制

输出

<code>b'\\n\\n\\n<title>\\nA simple example page\\n/<title>\\n\\n\\n

\\nHere is some simple content for this page.\\n

\\n\\n\\n'/<code>


Python 爬虫 – 使用requests抓取网页


分享到:


相關文章: