热门搜索 :
考研考公
您的当前位置:首页正文

Python笔记1:beautifulSoup路径确定方法 和

来源:东饰资讯网

week1 1_2 code of video
简易爬虫例子
先上代码:

from bs4 import BeautifulSoup

data = []
path = './web/new_index.html'

with open(path, 'r') as f:
    Soup = BeautifulSoup(f.read(), 'html.parser')#如果没有安装lxml,则用html.parser
    #网页的标题的CSS路径 body > div.main-content > ul > li:nth-child(1) > div.article-info > h3 > a
    #好用的备份titles = Soup.select('ul > li > div.article-info > h3 > a')
    titles = Soup.select('body > div > ul > li > div > h3 > a')
    #body > div.main-content > ul > li:nth-child(1) > img
    #好用的备份 pics = Soup.select('ul > li > img')
    pics = Soup.select('body > div > ul > li > img')
    descs = Soup.select('ul > li > div.article-info > p.description')
    rates = Soup.select('ul > li > div.rate > span')
    cates = Soup.select('ul > li > div.article-info > p.meta-info')

for title, pic, desc, rate, cate in zip(titles, pics, descs, rates, cates):
    info = {
        'title': title.get_text(),
        'pic': pic.get('src'),
        'descs': desc.get_text(),
        'rate': rate.get_text(),
        'cate': list(cate.stripped_strings)#stripped_strings过滤空格和空行内容
    }
    data.append(info)

for i in data:#取出一个个data
    if len(i['rate']) >= 3:#如果data中的属性rate大于3
        print(i['title'], i['cate'])

问题记录:
1)路径寻找。
在图片上右键选择审查元素,然后如下图选择复制。


Paste_Image.png

得到字符如下:

body > div.main-content > ul > li:nth-child(1) > img

这样的路径放在程序里面不可用。

pics = Soup.select('ul > li > img')

改成这样最精简的把后面的都删掉就可以用了。

pics = Soup.select('body > div > ul > li > img')

更新:
利用copy selector时报错出现:
NotImplementedError: Only the following pseudo-classes are implemented: nth-of-type.


解决办法为:nth-child改为nth-of-type

2)zip函数:
zip函数接受任意多个(包括0个和1个)序列作为参数,返回一个tuple列表。

x = [1, 2, 3]
y = [4, 5, 6]
z = [7, 8, 9]
xyz = zip(x, y, z)
print xyz#这个例子是Python2的。

运行的结果是:

[(1, 4, 7), (2, 5, 8), (3, 6, 9)]

想象成

鸡蛋 = [1, 2, 3]
西红柿 = [4, 5, 6]
油 = [7, 8, 9]
西红柿炒鸡蛋 = zip(鸡蛋, 西红柿, 油)
print 西红柿炒鸡蛋

运行的结果是:

[(1, 4, 7), (2, 5, 8), (3, 6, 9)]#代表不同搭配三盘番茄炒蛋
#这样就记住zip函数的使用方法
Top