网络爬虫基础练习
import requests newsurl = 'http://localhost:63342/bd/aaa.html?_ijt=7pd1hi6n7j1ue90de4jivbr31k' res = requests.get(newsurl) # 返回response对象 res.encoding = 'utf-8' print(res.text) from bs4 import BeautifulSoup soup = BeautifulSoup(res.text, 'html.parser') # 取出a标签的链接 print(soup.a.attrs['href']) # 取出h1标签的文本 print(soup.h1.text) # 取出所有li标签的所有内容 for i in soup.select('li'): print(i.contents) # 取出第2个li标签的a标签的第3个div标签的属性 print(soup.select('li')[1].a.select('div')[2].attrs) # 取出一条新闻的标题、链接、发布时间、来源 print('标题:'+soup.select('.news-list-title')[0].text) print('链接:'+soup.select('li')[2].a.attrs['href']) print('发布时间:'+soup.select('.news-list-info')[0].contents[0].text) print('来源:'+soup.select('.news-list-info')[0].contents[1].text)