requests库如何获取网页
时间: 2024-06-01 07:03:14 浏览: 11
Requests库可以通过发送HTTP请求来获取网页。可以使用requests.get()函数发送GET请求并获取响应。例如:
```
import requests
url = 'http://www.example.com'
response = requests.get(url)
print(response.text)
```
在这个例子中,我们使用requests.get()函数发送了一个GET请求到URL为'http://www.example.com'的网页,并将响应存储在response变量中。我们可以通过response.text属性来获取网页的源代码。
相关问题
python requests 获取网页代码
好的,以下是使用 Python requests 库获取网页代码的示例代码:
```
import requests
url = 'https://www.example.com'
response = requests.get(url)
if response.status_code == 200:
html = response.text
print(html)
else:
print('Failed to get the web page')
```
你可以将 `url` 替换成你要获取的网页地址,运行该代码即可输出该网页的代码。
使用 requests 库爬取静态网页
使用库爬取静态网页可以按照以下步骤进行:
1. 首先,确保已经安装了requests库。可以使用pip命令来安装,如:pip install requests。
2. 导入requests库,可以使用import语句导入requests库。
3. 使用get方法来获取目标网页的内容。get方法接受一个参数,即目标网页的URL。例如:r = requests.get("https://example.com")。
4. 查看响应的状态码,通过r.status_code来获取。状态码200表示网页已经获取成功。
5. 设置编码方式,通过r.encoding来进行设置。可以根据http的header中猜测的响应内容的编码方式来设置。通常情况下,可以将编码方式设置为utf-8。
6. 获取网页的文本内容,通过r.text来获取。这样就可以得到静态网页的文本内容了。