【问题标题】:Python BS4 Not Retrieving ResultsPython BS4 不检索结果
【发布时间】:2018-01-07 11:29:48
【问题描述】:

使用下面的代码,我可以毫无问题地获取“汤”。我的目标是最终在汤对象中获取标题,但我无法弄清楚如何去做。除了下面,我还尝试了各种汤['results']、soup.results、soup.get_text().results .. 等的迭代,但不知道如何得到它。当然,我可以做 soup.get_text() ...(对字符串“title”的某种搜索功能,但感觉必须有一个内置方法。

55)get_title()
     54     ipdb.set_trace()
---> 55     title = soup.html.head.title.string
     56     title = re.sub(r'[^\x00-\x7F]+',' ', title)

ipdb> type(soup)
<class 'bs4.BeautifulSoup'>
ipdb> soup.title
ipdb> print soup.title
None
ipdb> soup
{"status":"OK","copyright":"Copyright (c) 2018 The New York Times Company. All Rights Reserved.","section":"home","last_updated":"2018-01-07T06:19:00-05:00","num_results":42,"results":[{"section":"Briefing","subsection":"",**"title":"Trump, Palestinians, Golden Globes: Your Weekend Briefing"**, ....

代码

from __future__ import division

import regex as re
import string
import urllib2

from bs4 import BeautifulSoup
from cookielib import CookieJar
import ipdb

PARSER_TYPE = 'html.parser'

def get_title(url):
    cj = CookieJar()
    opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
    p = opener.open(url)
    soup = BeautifulSoup(p.read(), PARSER_TYPE) # This loads fine
    ipdb.set_trace()
    title = soup.html.head.title.string # This is sad
    title = re.sub(r'[^\x00-\x7F]+',' ', title)
    return title

【问题讨论】:

  • 向我们展示您尝试抓取的 HTML(包含标题的部分)

标签: python beautifulsoup html-parsing


【解决方案1】:

看看p.read() 返回什么。你会发现它不是 HTML,它是一个 JSON 字符串。您无法使用 HTML 解析器成功解析 JSON,但是,您可以使用 JSON 解析器,例如 json 包中提供的解析器。

import json

p = opener.open(url)
response = json.loads(p.read())

跟随response 将引用字典。然后,您可以使用字典访问方法来提取特定的数据:

title = response['results'][0]['title']

请注意,response['results'] 本身就是 list,因此您需要获取该列表的第一个元素(至少对于您展示的示例而言)。 response['results'][0] 然后给出第二个嵌套字典,其中包含您想要的数据。使用title 键进行查找。

由于结果包含在一个列表中,您可能需要遍历该列表来处理每个结果:

for result in response['results']:
    print(result['title'])

如果某些结果没有标题键,您可以使用dict.get() 执行查找而不会引发异常:

for result in response['results']:
    print(result.get('title'))

【讨论】:

  • 效果很好!非常感谢。
猜你喜欢
  • 2019-08-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多