python的基础爬虫(利用requests和bs4)

1、将请求网上资源:

1 import requests
2 res=requests.get('http://*******')
3 res.encoding='utf-8'
4 print(res.text)

这里面使用requests的get方法来获取html,具体是get还是post等等要通过网页头信息来查询:

比如百度的方法就是可以利用get得到。

2、将得到的网页利用BeautifulSoup进行剖析

1 from bs4 import BeautifulSoup
2 soup=BeautifulSoup(res.text,'html.parser')
3 print(soup)#可以看到网页的内容
4 for news in soup.select('.news-item'):#爬取一些新闻信息
5     header=news.select('h1')[0].text#新闻标题
6     time=news.select('.time')[0]#时间
7     print(header,time)

这里面需要注意的是结点的问题,在查看网页的源代码的时候要分清信息存储的位置,一步一步进行剖析,合理使用for循环。

原文地址:https://www.cnblogs.com/baojinjin/p/6819389.html