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

一、将请求网上资源:html

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

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

好比百度的方法就是能够利用get获得。spa

二、将获得的网页利用BeautifulSoup进行剖析code

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循环。htm

相关文章
相关标签/搜索