练习本地,还是自己写的,没什么含量,但还是需要记录下
爬取图片,标题,标签,内容,分数
//各自的Copy_selector如下
图片:body > div.main-content > ul > li:nth-child(1) > img
标题:body > div.main-content > ul > li:nth-child(1) > div.article-info > h3 > a
内容:body > div.main-content > ul > li:nth-child(1) > div.article-info > p.description
分数:body > div.main-content > ul > li:nth-child(1) > div.rate > span
标签:body > div.main-content > ul > li:nth-child(2) > div.article-info > p.meta-info > span:nth-child(2)
代码如下:
#导入BeautifulSoup库
from bs4 import BeautifulSoup
#空数组
dataArray = [ ]
#解析本地网页
with open('/Users/wangyi/代码练习/Python/解析网页中的元素/web/new_index.html','r') as we_data:
Soup = BeautifulSoup(we_data,'lxml')
#打印解析是否成功
# print(Soup)
# 图片
images = Soup.select('body > div.main-content > ul > li > img')
# 标题
titles = Soup.select('body > div.main-content > ul > li > div.article-info > h3 > a')
# 内容
contents = Soup.select('body > div.main-content > ul > li > div.article-info > p.description')
# 分数
fractions = Soup.select('body > div.main-content > ul > li > div.rate > span')
# 标签
labels = Soup.select('body > div.main-content > ul > li > div.article-info > p.meta-info')
#打印抓取到的数据
#print(images,titles,contents,fractions,labels,sep='\n=========\n')
#遍历添加到data字典里
for image,title,content,fraction,label in zip(images,titles,contents,fractions,labels):
data = {
'image' : image.get('src'),
'title' : title.get_text(),
'content' : content.get_text(),
'label': list(label.stripped_strings),
'fraction' : fraction.get_text()
}
#添加到数组中
dataArray.append(data)
#遍历数组
for i in dataArray:
#获取大于3的文章
if float(i['fraction']) > 3:
#打印文章标题和内容
print(i['title'],'======',i['content'])