Python网络爬虫:Requests库:get函数使用方法

Requests库的七个主要方法:

 r = requests.get(url) :

      构造一个向服务器请求资源的Request对象(Request),并且get方法返回一个包含服务器资源的Response对象;

requests.get函数的完整参数如下:

        requests.get(url, params = None, **kwargs)

        url: 拟获取页面的url链接

        params: url中额外参数,字典或字节流格式,可选

        **kwargs: 12个  访问的参数

Requests库的2个重要的对象 Request 和 Response对象(Response对象包含爬虫返回的所有内容)

>>> import requests #导入requests库
>>> r = requests.get("http://www.baidu.com") 
>>> print(r.status_code) #检测请求的状态码,200表示请求成功
200
>>> type(r)
<class 'requests.models.Response&
  • 4
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
1. 网站选择 我们可以选择网站 https://finance.yahoo.com/quote/GOOG/history/ 进行股票数据的采集。该网站提供了谷歌公司(GOOG)的股票历史数据,包括每日的开盘价、收盘价、最高价、最低价、成交量和调整后的收盘价等。 2. 网页分析 我们首先打开该网站,可以看到页面上有一个日期选择器,可以选择需要采集的时间范围。我们可以利用 Pythonrequests 和 BeautifulSoup 来模拟网页请求和解析网页内容。 3. 代码实现 首先,我们需要导入必要的。 ```python import requests from bs4 import BeautifulSoup ``` 然后,我们需要定义一个函数,用于获取网页内容。该函数接收一个 URL 参数,并返回该 URL 对应的网页内容。 ```python def get_page(url): headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'} response = requests.get(url, headers=headers) if response.status_code == 200: return response.content else: return None ``` 接下来,我们需要编写一个函数,用于解析网页内容。该函数接收一个 HTML 参数,并返回一个字典列表,包含每日的股票数据。 ```python def parse_page(html): soup = BeautifulSoup(html, 'html.parser') table = soup.find('table', {'data-test': 'historical-prices'}) rows = table.tbody.find_all('tr') data = [] for row in rows: cols = row.find_all('td') if len(cols) == 7: date = cols[0].text.strip() open_price = cols[1].text.strip() high_price = cols[2].text.strip() low_price = cols[3].text.strip() close_price = cols[4].text.strip() adj_close_price = cols[5].text.strip() volume = cols[6].text.strip() data.append({ 'date': date, 'open_price': open_price, 'high_price': high_price, 'low_price': low_price, 'close_price': close_price, 'adj_close_price': adj_close_price, 'volume': volume }) return data ``` 最后,我们需要编写一个主函数,用于调用上述两个函数,并输出采集的股票数据。 ```python def main(): base_url = 'https://finance.yahoo.com/quote/GOOG/history?p=GOOG' start_date = '20220101' end_date = '20220131' url = '{}&period1={}&period2={}&interval=1d&filter=history&frequency=1d'.format(base_url, start_date, end_date) html = get_page(url) data = parse_page(html) for item in data: print(item) ``` 我们可以将上述代码保存为一个 Python 文件,运行该文件即可输出采集的股票数据。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值