用json爬行的python美丽的汤

时间:2015-10-09 09:54:31

标签: python html json request beautifulsoup

我是python中的beautifulsoup的新手,我试图从网站中提取某些信息。深层链接和标题

我使用beautifulsoup来提取json并获得了我的beautifulsoup.beautifulsoup变量汤。

但我还没有设法提取所需的信息。

正在收获HTML块:

<div class="activities-list horizontal">
<article data-href="http://www.getyourguide.de/london-l57/windsor-bath-und- stonehenge-tagesausflug-ab-london-t977/" id="t977" class="activity-card activity-card-horizontal
">
<div class="activity-card-content">
<a class="activity-card-link" href="http://www.getyourguide.de/london-l57/windsor-bath-und-stonehenge-tagesausflug-ab-london-t977/">
<div class="activity-card-image-container">
<img src="http://img.getyourguide.com/img/tour_img-206771-70.jpg" data- role="cover" alt="" />
</div>
<div class="activity-card-details">
<header class="activity-card-header">
<h3 class="activity-card-title">
Stonehenge, Windsor und Bath - Tagesausflug ab London
</h3>
<div class="activity-rating">
<span class="rating" title="Bewertung: 3,9 von 5">
<span class="rating-stars s30"></span>
<span class="rating-total">13 Bewertungen</span>
</span>                     </div>
</header>
<p class="activity-small-description">Verlassen Sie London und entdecken Sie    Reize der englischen Landschaft auf einer Ganztagestour, die Sie zu berühmten,   historischen Orten führt.…</p>
<div class="activity-info activity-duration">
<span class="activity-info-label activity-duration-label">

的Dauer:                10 Stunden                              抗体           €75                    Jetzt buchen                         

我想解析deeplinks(href)和title(activity-card-title)。到目前为止,这是我的逻辑:

 response = urlopen("http://www.getyourguide.de/s/search.json?    q=London&page=8")
 content = response.read()
 soup = BeautifulSoup(content)
 newDictionary = json.loads(str(soup))['activities'].get("href")
 print(newDictionary)

结果:

  newDictionary = json.loads(str(soup))['activities'].get("href")
  AttributeError: 'str' object has no attribute 'get'

感谢任何反馈:)

2 个答案:

答案 0 :(得分:1)

response = urllib2.urlopen(link)
html = response.read()
soup = BeautifulSoup(html,'html.parser',from_encoding='utf-8')

用于深层链接:

links = soup.find_all('a',href=True)
标题

titles = soup.find_all('div',{'class':'activity-card-title'})

如果块中只有1个标题,则只能找到

title  = soup.find('div',{'class':'activity-card-title'})

答案 1 :(得分:0)

你得到的属性错误是因为你试图用json加载整个汤,这是无法完成的。看起来你想要<p>标签的内容,然后你可以将它加载到json中。你可以像这样得到它,并像普通字典一样获得活动值。

activities = json.loads(soup.find('p').text)['activities']

然而它变得有点奇怪,因为我们不再处理汤了,我们只是有一个看起来像某个html的大字符串。所以我们可以用它来制作新的汤,并从最终的汤中获得深层链接和标题。

newsoup = BeautifulSoup(activities)

links = newsoup.find_all('a', href=True)
deeplinks = [ a['href'] for a in links ]

titles = newsoup.find_all('h3', 'activity-card-title')
相关问题