鍍金池/ 問(wèn)答/Python/ 爬取豆瓣電影Top250,一個(gè)問(wèn)題

爬取豆瓣電影Top250,一個(gè)問(wèn)題

之前是用正則寫(xiě)的,雖然成功爬取了,但是要考慮的特殊情況太多,很煩。后來(lái)有人建議用xpath,所以學(xué)習(xí)了相關(guān)知識(shí),改寫(xiě)原先用正則寫(xiě)的代碼,但是碰到了一個(gè)問(wèn)題
網(wǎng)頁(yè)的源代碼如下:

                    <div class="hd">
                        <a  class="">
                            <span class="title">肖申克的救贖</span>
                                    <span class="title">&nbsp;/&nbsp;The Shawshank Redemption</span>
                                <span class="other">&nbsp;/&nbsp;月黑高飛(港)  /  刺激1995(臺(tái))</span>
                        </a>


                            <span class="playable">[可播放]</span>
                    </div>
                    <div class="bd">
                        <p class="">
                            導(dǎo)演: 弗蘭克·德拉邦特 Frank Darabont&nbsp;&nbsp;&nbsp;主演: 蒂姆·羅賓斯 Tim Robbins /...<br>
                            1994&nbsp;/&nbsp;美國(guó)&nbsp;/&nbsp;犯罪 劇情
                        </p>

                        
                        <div class="star">
                                <span class="rating5-t"></span>
                                <span class="rating_num" property="v:average">9.6</span>
                                <span property="v:best" content="10.0"></span>
                                <span>987073人評(píng)價(jià)</span>
                        </div>

                            <p class="quote">
                                <span class="inq">希望讓人自由。</span>
                            </p>
                    </div>

我現(xiàn)在想提取導(dǎo)演演員那塊的信息,根據(jù)所在位置我的代碼如下(導(dǎo)演存在dirc中)):

selc = etree.HTML(html)
infos = selc.xpath('//div[@class="info"]')
for a in infos:
    dirc = a.xpath('div[@class="bd]/p[@class=""]/text()')

但這樣寫(xiě)不對(duì),網(wǎng)上的代碼如下:

info = i.xpath('div[@class="bd"]/p[1]/text()') 

我這樣寫(xiě)和網(wǎng)上的不是一樣嗎?為什么我的不對(duì)?求高手指點(diǎn),謝謝

回答
編輯回答
枕頭人

div[@class="bd"]/p[1]是選取class為bd的div孩子節(jié)點(diǎn)的第一個(gè)p節(jié)點(diǎn)

2017年10月24日 01:30
編輯回答
避風(fēng)港

網(wǎng)上的這種方式更加合理,
info = i.xpath('div[@class="bd"]/p[1]/text()')
另外你的這種方式:

selc = etree.HTML(html)
infos = selc.xpath('//div[@class="info"]')
for a in infos:
    dirc = a.xpath('./div[@class="bd]/p[@class=""]/text()')  # 這樣是否可行

但是我還是覺(jué)得dirc = a.xpath('./div[@class="bd]/p[1]/text()')更好

2018年4月14日 08:50
編輯回答
涼汐
import requests
from lxml import etree


start_url = "https://movie.douban.com/top250?start="

htmlStr = requests.get(start_url).text

tree = etree.HTML(htmlStr)

infos = tree.xpath('//ol[@class="grid_view"]/li//div[@class="bd"]/p[1]')

for i in infos:
    print(i.xpath('.//text()'))

試試在chrome里裝個(gè)XPath Helper插件,在這里面邊寫(xiě)可以邊看到匹配出來(lái)的內(nèi)容,這樣就知道自己寫(xiě)到哪個(gè)位置出問(wèn)題了。

2018年3月4日 05:17