2014-10-04 3 views
3

1/Я пытаюсь извлечь часть скрипта с помощью красивого супа, но он ничего не печатает. Что не так ?Извлечь содержимое <Script with BeautifulSoup

URL = "http://www.reuters.com/video/2014/08/30/woman-who-drank-restaurants-tainted-tea?videoId=341712453" 
oururl= urllib2.urlopen(URL).read() 
soup = BeautifulSoup(oururl) 

for script in soup("script"): 
     script.extract() 

list_of_scripts = soup.findAll("script") 
print list_of_scripts 

2/Цель состоит в том, чтобы извлечь значение атрибута "стенограмма":

<script type="application/ld+json"> 
{ 
    "@context": "http://schema.org", 
    "@type": "VideoObject", 
    "video": { 
     "@type": "VideoObject", 
     "headline": "Woman who drank restaurant&#039;s tainted tea hopes for industry...", 
     "caption": "Woman who drank restaurant&#039;s tainted tea hopes for industry...", 
     "transcript": "Jan Harding is speaking out for the first time about the ordeal that changed her life.    SOUNDBITE: JAN HARDING, DRANK TAINTED TEA, SAYING:    \"Immediately my whole mouth was on fire.\"    The Utah woman was critically burned in her mouth and esophagus after taking a sip of sweet tea laced with a toxic cleaning solution at Dickey's BBQ.    SOUNDBITE: JAN HARDING, DRANK TAINTED TEA, SAYING:    \"It was like a fire beyond anything you can imagine. I mean, it was not like drinking hot coffee.\"    Authorities say an employee mistakenly mixed the industrial cleaning solution containing lye into the tea thinking it was sugar.    The Hardings hope the incident will bring changes in the restaurant industry to avoid such dangerous mixups.    SOUNDBITE: JIM HARDING, HUSBAND, SAYING:    \"Bottom line, so no one ever has to go through this again.\"    The district attorney's office is expected to decide in the coming week whether criminal charges will be filed.", 

ответ

8

extract удалить тег из йот. Вот почему вы получаете пустой список.


Найти script с атрибутом type="application/ld+json" и декодировать его с помощью json.loads. Затем вы можете получить доступ к данным, таким как структура данных Python. (dict для приведенных данных)

import json 
import urllib2 

from bs4 import BeautifulSoup 

URL = ("http://www.reuters.com/video/2014/08/30/" 
     "woman-who-drank-restaurants-tainted-tea?videoId=341712453") 
oururl= urllib2.urlopen(URL).read() 
soup = BeautifulSoup(oururl) 

data = json.loads(soup.find('script', type='application/ld+json').text) 
print data['video']['transcript'] 
+0

Когда я пытаюсь по этой ссылке: [ссылка] (http://www.reuters.com/article/2014/08/26/ichitan-group-indonesia-green- tea-idUSL3N0QW27F20140826), используя этот код: data = soup.findAll ('span', id = 'articleText') Я получаю пустое содержимое снова, даже если я не использую extract:

+0

@laihob, Это другой вопрос. Не так ли? Во всяком случае, попробуйте: 'print '' .join (soup.find ('span', id = 'articleText'). Strings)' – falsetru

+0

Да, предыдущий вопрос работал хорошо. На этот раз я хочу извлечь статью в этой ссылке, которая находится внутри , я попробую то, что вы сказали сейчас. thx –

Смежные вопросы