首頁  >  問答  >  主體

python - 怎么从BeautifulSoup得到的ResultSet里搜索想要的部分?

python脚本里的语句是

from bs4 import BeautifulSoup
import urllib2

response = urllib2.urlopen('http://xxxxxx')
html = response.read()
soup = BeautifulSoup(html)

res = soup.find_all(class_='pro-detail-price')

得到的res是ResultSet类型,print结果是:

[<p class="pro-detail-price">最低价格:<span>4399.0</span>(天猫旗舰店)
<p class="pro-detail-trend">
<iframe frameborder="0" height="210" scrolling="no" src="http://tool.manmanbuy.com/historyPro.aspx?w=290&amp;amp;h=210&amp;m=1&amp;e=0&amp;scroll=0&amp;id=327958" width="290"></iframe>
</p>
</p>]

如果想在这个ResultSet里找到特定的标签改用什么办法呢? 比如找到<span>4399.0</span>里的4399.0

黄舟黄舟2742 天前1114

全部回覆(6)我來回復

  • PHP中文网

    PHP中文网2017-04-17 17:11:55

    res = soup.find(class_='pro-detail-price').find('span').string

    這麼可以嗎?

    回覆
    0
  • 巴扎黑

    巴扎黑2017-04-17 17:11:55

    我記得find只會回傳第一個符合的結果,findAll才會回傳ResultSet
    所以find結果應該可以直接res.span.string啊,實在不行就都res[0].span .string吧

    回覆
    0
  • 大家讲道理

    大家讲道理2017-04-17 17:11:55

    find_all()find()都不好用,bs最好用的是select(),也就是CSS選擇器。
    你已經取得了一個大框架吧,例如它是soup中的一個Tag,然後:find_all()find()都不好用,bs最好用的是select(),即CSS选择器。
    你已经获取了一个大框架吧,比如它是soup中的一个Tag,然后:

    results = tag.select('p[class="pro-detail-price"] span')

    你这个例子里,results[0] rrreee

    你這個例子裡,results[0]就是這個指定的標籤了。 🎜

    回覆
    0
  • 大家讲道理

    大家讲道理2017-04-17 17:11:55

    from bs4 import BeautifulSoup
    import urllib2
    
    response = urllib2.urlopen('http://xxxxxx')
    html = response.read()
    soup = BeautifulSoup(html)
    
    res = soup(class_='pro-detail-price')
    
    for sp in res:
        print sp.span.string
    

    胡亂試了一下,改成這樣的程式碼輸出結果是4399.0,但是希望大神能提供更優的方式,謝謝

    回覆
    0
  • 怪我咯

    怪我咯2017-04-17 17:11:55

    在find找到的結果裡,可以用CSS選擇器select進行下一的了定位查找。

    回覆
    0
  • 怪我咯

    怪我咯2017-04-17 17:11:55

    雷雷

    回覆
    0
  • 取消回覆