【问题标题】:Scrape content in json format - Python以 json 格式抓取内容 - Python
【发布时间】:2018-03-29 01:50:47
【问题描述】:

我正在尝试使用 Python 3.5 抓取像 this 这样的页面。我已经使用 BeautifulSoup 抓取了它的内容。我在抓取尺寸数量时遇到问题。在此特定页面中,尺寸数量为 9(FR 80 A、FR 80 B、FR 80 C 等)。我想这些信息是 json 格式的。我正在尝试使用 json 包,但找不到“开始”和“结束”。 我的代码如下所示:

import requests
import json

page = requests.get('https://www.laperla.com/fr/en/cfiplm000566-bgw532.html')
content = page.text    
start = content.find('spConfig') + ...
end = ...    
data = json.loads(content[start:end])
sizes = data['attributes']['179']['options']
print(len(sizes))

正确的输出应该是“9”,因为有 9 种尺寸。我不想使用 selenium 或此类软件包。那么,哪个是正确的“开始”和“结束”?有没有比我尝试做的更好的方法来抓取这些数据?

【问题讨论】:

    标签: python json web-scraping beautifulsoup


    【解决方案1】:

    1 .迭代所有script标签并搜索目标json

    2 。使用regex抓取startend

    3 .使用json模块

    for i in soup.select('script'):
        if 'Product.Config' in str(i):
            data = re.search(r'(?is)(Product\.Config\()(.*?)(\))',str(i)).group(2)
    
    json_data = json.loads(data)
    print(len(json_data['attributes']['179']['options']))
    9
    

    【讨论】:

      猜你喜欢
      • 2019-07-19
      • 1970-01-01
      • 1970-01-01
      • 2021-07-06
      • 2011-02-14
      • 1970-01-01
      • 1970-01-01
      • 2020-09-06
      相关资源
      最近更新 更多