爬虫【1】打开网站,获取信息

爬虫【1】打开网站,获取信息

如何向网站发起请求并获取响应对象?

urllib.request.urlopen
  • 作用

向网站发起请求并获取响应对象

  • 参数
url:需要爬取的URL地址
timeout: 设置等待超时时间,指定时间内未得到响应抛出超时异常
  • 第一个爬虫程序

打开浏览器,输入百度地址(http://www.baidu.com/),得到百度的响应

import urllib.request

# urlopen() : 向URL发请求,返回响应对象
response=urllib.request.urlopen('http://www.baidu.com/')
# 提取响应内容
html = response.read().decode('utf-8')
# 打印响应内容
print(html)
  • 响应对象(response)方法
1bytes = response.read() # read()得到结果为 bytes 数据类型
2、string = response.read().decode() # decode() 转为 string 数据类型
3、url = response.geturl() # 返回实际数据的URL地址
4、code = response.getcode() # 返回HTTP响应码
# 补充
5、string.encode() # bytes -> string
6bytes.decode()  # string -> bytes
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要使用Python爬虫获取网站信息,可以使用以下几种方式: 1. 使用urllib/urllib2库:这是Python内置的库,可以用于发送HTTP请求获取网页内容。你可以使用urllib库中的urlopen函数来打开一个URL,并使用read方法读取网页内容。例如: ```python import urllib.request response = urllib.request.urlopen('http://www.example.com') html = response.read() print(html) ``` 2. 使用httplib库:这也是Python内置的库,可以用于发送HTTP请求。你可以使用httplib库中的HTTPConnection类来建立与服务器的连接,并使用getresponse方法获取服务器的响应。例如: ```python import http.client conn = http.client.HTTPConnection("www.example.com") conn.request("GET", "/") response = conn.getresponse() html = response.read() print(html) ``` 3. 使用Requests库:这是一个第三方库,提供了更简洁和方便的方式来发送HTTP请求。你可以使用requests库中的get方法来发送GET请求,并使用text属性获取响应的内容。例如: ```python import requests response = requests.get('http://www.example.com') html = response.text print(html) ``` 以上是三种常用的Python爬虫获取网站信息的方式,你可以根据自己的需求选择其中一种来实现。 #### 引用[.reference_title] - *1* *2* [网络爬虫有什么用?怎么爬?手把手教你爬网页(Python代码)](https://blog.csdn.net/zw0Pi8G5C1x/article/details/89507476)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] - *3* [Java调用Python爬虫获取信息](https://blog.csdn.net/m0_55415167/article/details/126944262)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值