看了一些教程视频,所以今天做一个简单的爬虫练习
用的是request+bs4
request用于获取网页内容
bs4用于截取需要的网页内容
pandas用于展示获取到的数据
import requests
import pandas
from bs4 import BeautifulSoup
import sqlite3
res = requests.get('https://www.btime.com/?src=tab_web')
res.encoding = 'utf-8'
soup = BeautifulSoup(res.text, 'html.parser')
content = soup.select('.list-group-recommend')
print(content)
#获取对象内容
all = content[0].select('a')
# print(all[2].text)
obj_arr = []
#all['title'] = content[0].select('a')['title']
for a in all:
obj = {}
obj['link'] = a['href']
obj['title'] = a['title']
obj_arr.append(obj)
print(obj_arr)
df = pandas.DataFrame(obj_arr)
df
结果为:
注意一点 python中对对象的引用和java有些区别,当我将对象定义在循环外时,for循环将数据作为对象的属性放入集合中,但是获取到的集合都是同一条数据。但是在java中这样做是没有问题的。
另外,今天本来是想爬取微博网站的,但是微博的内容是通过ajax获取到的,用这种方法不能直接获取到。明天继续研究爬虫,争取爬取出微博的内容。
愿我们一起加油!