【问题标题】:How to get the specific content in Python with BeautifulSoup?如何使用 BeautifulSoup 获取 Python 中的具体内容?
【发布时间】:2017-09-16 21:32:05
【问题描述】:

我是 Python 新手,我正在使用 BeautifulSoup 在 Python 中编写一个小爬虫,以便从网页中获取地址。我附上了它的图片 enter image description here

    </div>
    </div>
    <div data-integration-name="redux-container" data-payload='{"name":"LocationsMapList","props":{"locations":[{"id":17305,"company_id":106906,"description":"","city":"New York","country":"United States","address":"5 Crosby St  3rd Floor","state":"New York","region":"","latitude":40.719753,"longitude":-74.0001954,"hq":true,"created_at":"2015-01-19T01:32:16.317Z","updated_at":"2016-05-05T07:57:19.282Z","zip_code":"10013","country_code":"US","full_address":"5 Crosby St  3rd Floor, New York, 10013, New York, USA","dirty":false,"to_params":"new-york-us"}]},"storeName":null}' data-rwr-element="true">

我使用 BeautifulSoup 获得了完整的内容,但我不知道如何提取“full_address”的内容。我看到它在“div”中,但我不知道下一步该做什么。

links = soup.find_all('div')

非常感谢!

【问题讨论】:

  • (请将您的代码添加为文本而不是图片)
  • 我添加了它。谢谢!
  • 'data-payload'属性是json,所以使用json.loads
  • 如果您不熟悉 html 的命名法 - W3C TutorialThe BeautifulSoup docs 有一些很好的基础 - 如果您通读它并牢记您的问题,您可能会开始看到解决方案。
  • 您可能还想花一些时间通过the Python Tutorial 了解可供您使用的工具。请阅读How to Askminimal reproducible example

标签: python web beautifulsoup screen-scraping


【解决方案1】:

可以使用json解析数据:

#!/usr/bin/env python 

from bs4 import BeautifulSoup
import json

data = '''
</div>
    </div>
    <div data-integration-name="redux-container" data-payload='{"name":"LocationsMapList","props":{"locations":[{"id":17305,"company_id":106906,"description":"","city":"New York","country":"United States","address":"5 Crosby St  3rd Floor","state":"New York","region":"","latitude":40.719753,"longitude":-74.0001954,"hq":true,"created_at":"2015-01-19T01:32:16.317Z","updated_at":"2016-05-05T07:57:19.282Z","zip_code":"10013","country_code":"US","full_address":"5 Crosby St  3rd Floor, New York, 10013, New York, USA","dirty":false,"to_params":"new-york-us"}]},"storeName":null}' data-rwr-element="true">
'''

soup = BeautifulSoup(data, 'html.parser')
for i in soup.find_all('div', attrs={'data-integration-name':'redux-container'}):
    info = json.loads(i.get('data-payload'))
    for i in info['props']['locations']:
        print i['address']

【讨论】:

  • 它说:KeyError: 'locations'
  • @Laura 对于我的解决方案,我假设您尝试解析的数据与您帖子中的数据完全相同。您的数据与您发布的错误的原因是否相同,您的数据中似乎不存在“位置”?还可以查看您可以执行的密钥print i.keys()
  • 也许将其限制为具有data-integration-name="redux-container" 属性的div
  • @Laura 答案更多是为了演示json 的使用以及如何解析此类数据。现在您应该能够进行一些研究并将其应用于不同的数据。此外,如 cmets 部分所述,您应该非常仔细地阅读 bs4 文档
  • @coder,它仍然显示相同的错误。不过非常感谢!我会回去阅读 bs4 文档。
猜你喜欢
  • 2022-11-14
  • 2015-03-11
  • 2020-09-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多