第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

BeautifulSoup 4:從不同的ptag提取多個標(biāo)題和鏈接

BeautifulSoup 4:從不同的ptag提取多個標(biāo)題和鏈接

九州編程 2021-06-01 09:58:33
HTML代碼:<div>    <p class="title">       <a href="/news/123456">title_1</a>     </p></div><div>    <p class="title">       <a href="/news/789000">title_2</a>     </p></div>我的代碼:def web(WebUrl):    site = urlparse(WebUrl)    code = requests.get(WebUrl)    plain = code.text    s = BeautifulSoup(plain, "html.parser")    p_containers = s.find('p', {'class':'title'})    for title in s.find_all('p', {'class':'title'}):        line = title.get_text()        print(line)        for link in p_containers.find_all('a'):            line2 = link.get('href')            print(site.netloc + str(line2))嗨,大家好,我需要一些幫助,我的任務(wù)是從網(wǎng)頁中提取標(biāo)題和鏈接,我能夠提取標(biāo)題而不是鏈接。當(dāng)我嘗試抓取鏈接時,我只成功抓取了第一個鏈接,以下鏈接被忽略并替換為第一個抓取的鏈接。
查看完整描述

2 回答

?
HUX布斯

TA貢獻(xiàn)1876條經(jīng)驗 獲得超6個贊

您的代碼中有大部分位,但只有一點點錯了。我認(rèn)為獲取標(biāo)題和鏈接的最簡單方法是使用以下內(nèi)容。


site = """<div>

    <p class="title">

       <a href="/news/123456">title_1</a> 

    </p>

</div>


<div>

    <p class="title">

       <a href="/news/789000">title_2</a> 

    </p>

</div>"""


s = BeautifulSoup(site, "html.parser")


for title in s.find_all('p', {'class':'title'}):

    links = [x['href'] for x in title.find_all('a', href=True)]

    line = title.get_text()

    print(line)

    print(links)

您可以看到 links 對象是一個列表,以防萬一每個標(biāo)題都有多個鏈接。


查看完整回答
反對 回復(fù) 2021-06-01
?
慕碼人8056858

TA貢獻(xiàn)1803條經(jīng)驗 獲得超6個贊

嘗試這種方式將有助于從中查找所有值。


from bs4 import BeautifulSoup


text = """<div>

    <p class="title">

       <a href="/news/123456">title_1</a> 

    </p>

</div>


<div>

    <p class="title">

       <a href="/news/789000">title_2</a> 

    </p>

</div>

"""


soup = BeautifulSoup(text, 'html.parser')

for i in soup.find_all('p', attrs={'class': 'title'}):

    link = None

    if i.find('a'):

        link = i.find('a').get('href')

    print('Title:', i.get_text(strip=True), 'Link:', link)

# Output as:

# Title: title_1 Link: /news/123456

# Title: title_2 Link: /news/789000


查看完整回答
反對 回復(fù) 2021-06-01
  • 2 回答
  • 0 關(guān)注
  • 233 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號